var SERVERURL = 'http://www.yunping168.com/api/'; //麻

//////////七牛相关///////////

function qiNiuKeyName() {
    var qiNiuKey = new Date().getTime() + '.jpg';
    return qiNiuKey;
}

//////////////////////////////////////图片转换///////////////////////////////////////////////
function changeImggggggg1(img) {
    var imggggg = img + '?imageMogr2/thumbnail/!340x340r/gravity/Center/crop/340x340';

    return imggggg;
}

//两张图
function changeImggggggg2(img) {
    var imggggg = img + '?imageMogr2/thumbnail/!220x220r/gravity/Center/crop/220x220';

    return imggggg;
}

//三张图
function changeImggggggg3(img) {
    var imggggg = img + '?imageMogr2/thumbnail/!153x153r/gravity/Center/crop/153x153';

    return imggggg;
}

//视频的第一帧图片
var videoImg = '?x-oss-process=video/snapshot,t_1000,f_jpg,m_fast';
var imgUrl = 'https://develop-kingsuper.oss-cn-hangzhou.aliyuncs.com/';
var IMAGEURL = 'http://qiniu.xinliban.com/';
/**
 *  网络数据请求
 * @param {Object} url  链接的服务器地址
 * @param {Object} type   传递的是 GET  OR POST
 * @param {Object} params   参数   JSON 参数   values:JSON 参数    files 表示你要上传的文件
 * @param {Object} successFun   成功的执行方法
 * @param {Object} errorFun  失败的执行方法

 例子：
 var parame = {
		values : {
		}
	}
 doAjax(url, "POST", parame, function(successData) {
	//成功执行函数
	}, function(errorData) {
	//失败执行函数
	})

 */

var doAjax = function (url, type, params, successFun, errorFun) {

    console.log(localStorage.getItem("allUser") + '||||');

    if (localStorage.getItem("allUser")) {

        var alllArr=eval('(' + localStorage.getItem("allUser") + ')');

        var value = alllArr.user_token || '0';
        var userId = alllArr.user_id || '';
    } else {
        var value = '';
        var userId = '0';
    }

    if (params == null) {
        params = {};
    }

    var reqDate = Date.now();
    var appId = 'A6097314776331';
    var appkey = '6A3C022C-9171-00A1-943B-C9675EE1C3E0';
    var reqKey = MD5(appId + 'XW' + appkey + 'XW' + reqDate);
    // console.warn('Token' + JSON.stringify(allUser));
    // var Token = $api.getStorage('allUser')?$api.getStorage('allUser').user_token:'';
    var Token = MD5(userId + 'XW' + value + 'XW' + reqDate) || '';
    params.user_id = userId;
    // params.values.userId = user_id;
    // params.values.token = Token;
    params.value = Token;
    params.time = reqDate;
    params.reqKey = reqKey;
    // params.values.appId = appId;

    console.log('接口地址和入参！！' + url + '  ' + JSON.stringify(params));
    //  + "时间戳："+ reqDate + "加密key：" + reqKey);

    $.ajax({
      url:url,
      data:params,
      type:'post',
      cache:false,
      dataType:'json',
      success:function(ret) {
        console.log('接口成功返回！！' + JSON.stringify(ret));
        if (ret.status == '301') {
            if (localStorage.getItem("allUser")) {
                localStorage.removeItem('allUser')
            }
            openWindow('login_win','../../html/login_win.html');
            tanKuang('账号已在其他地方登录,请重新登录');
            return;
        } else {
            successFun(ret);
        }
       },
       error : function(err) {
        console.log('失败成功返回！！' + JSON.stringify(err));
        errorFun(err);
       }

       });





};


/**
 *安卓回退监听 type 用于主页和非主页
 例： AndroidBackEvent(1, function(data) {
      //成功返回
      });
 */
var exitFlag = false;
var AndroidBackEvent = function (type, successFun) {
    api.addEventListener({
        name: 'keyback'
    }, function (ret, err) {

        console.log('监听安卓回退返回！！' + JSON.stringify(ret));
        if (type == 1) {
            if (!exitFlag) {
                api.toast({
                    msg: '再按一次退出',
                    duration: 2000,
                    location: 'middle'
                });
                exitFlag = true;
            } else {
                api.closeWidget({
                    silent: true
                });
            }
            setTimeout(function () {
                exitFlag = false;
            }, 2000);

            successFun(ret);
        } else if (type == 2) {
            api.closeToWin({
                name: 'root1'
            });
        } else if (type == 3) {
            api.closeToWin({
                name: 'login_win'
            });

        } else if (type == 4) {
            var jsfun = 'initData()';
            api.execScript({
                name: 'person_win', //      frameName: 'my_information_frm',
                script: jsfun
            });
            api.closeWin();
        } else if (type == 5) {
            var jsfun = 'initData()';
            api.execScript({
                name: 'root1',
                frameName: 'main5_win',
                script: jsfun
            });
            api.closeToWin({
                name: 'root1'
            });
        } else {
            successFun(ret);
        }

    });
};

/*
 ** 时间戳转年月日+时分
 ** Date.parse(new Date());//当前时间毫秒数
 */
function changeTimeH(hisTime) {

    if (hisTime == '') {

        return '';
    }

    var newTime = new Date(hisTime);
    var newYear = newTime.getFullYear(); //年
    var newMonth = newTime.getMonth() + 1; //月
    var newDay = newTime.getDate(); //日
    var newHours = newTime.getHours(); //时
    var newMinutes = newTime.getMinutes(); //分
    var newSeconds = newTime.getSeconds(); //秒

    if (newMonth < 10) {
        newMonth = '0' + newMonth;
    }
    if (newDay < 10) {
        newDay = '0' + newDay;
    }

    if (newHours < 10) {
        newHours = '0' + newHours;
    }
    if (newMinutes < 10) {
        newMinutes = '0' + newMinutes;
    }
    if (newSeconds < 10) {
        newSeconds = '0' + newSeconds;
    }

    var timee = newYear + '-' + newMonth + '-' + newDay;
    return timee;
}

function changeTimeH1(timeStamp) {

    var replaceStr = '-'; //要替换的字符串
    var str = timeStamp; //要被替换的字符串

    var timeStamp = str.replace(new RegExp(replaceStr, 'gm'), '/');

    var newTime = new Date(timeStamp);

    var newYear = newTime.getFullYear(); //年
    var newMonth = newTime.getMonth() + 1; //月
    var newDay = newTime.getDate(); //日
    var newHours = newTime.getHours(); //时
    var newMinutes = newTime.getMinutes(); //分
    var newSeconds = newTime.getSeconds(); //秒

    if (newMonth < 10) {
        newMonth = '0' + newMonth;
    }
    if (newDay < 10) {
        newDay = '0' + newDay;
    }

    if (newHours < 10) {
        newHours = '0' + newHours;
    }
    if (newMinutes < 10) {
        newMinutes = '0' + newMinutes;
    }
    if (newSeconds < 10) {
        newSeconds = '0' + newSeconds;
    }

    //var timee = newHours+":"+newMinutes;
    var timee = newYear + '年' + newMonth + '月' + newDay + '日';
    return timee;
}

function changeTimeH2(timeStamp) {

    var newTime = new Date(timeStamp);
    var newYear = newTime.getFullYear(); //年
    var newMonth = newTime.getMonth() + 1; //月
    var newDay = newTime.getDate(); //日
    var newHours = newTime.getHours(); //时
    var newMinutes = newTime.getMinutes(); //分
    var newSeconds = newTime.getSeconds(); //秒

    if (newMonth < 10) {
        newMonth = '0' + newMonth;
    }
    if (newDay < 10) {
        newDay = '0' + newDay;
    }

    if (newHours < 10) {
        newHours = '0' + newHours;
    }
    if (newMinutes < 10) {
        newMinutes = '0' + newMinutes;
    }
    if (newSeconds < 10) {
        newSeconds = '0' + newSeconds;
    }

    //var timee = newHours+":"+newMinutes;
    var timee = newYear + '-' + newMonth + '-' + newDay + ' ' + newHours + ':' + newMinutes + ':' + newSeconds;
    return timee;
}

/*
 *
 * 时间判断
 *
 * 1小时之内显示时分，
 * 1天之后显示月日
 * 1年之后显示年月日
 *
 */

var dateDiff = function (hisTime, nowTime) {

    if (hisTime == null) {
        hisTime = '1900-01-01 00:00:00.0';
    }
    date = hisTime.substring(0, 19);
    date = date.replace(/-/g, '/');

    hisTime = Date.parse(new Date(date)); //时间转时间搓

    var now = nowTime ? nowTime : new Date().getTime(), diffValue = now - hisTime, result = '', minute = 1000 * 60,
        hour = minute * 60, day = hour * 24, halfamonth = day * 15, month = day * 30, year = month * 12,
        _year = diffValue / year,
        _month = diffValue / month, _week = diffValue / (7 * day), _day = diffValue / day, _hour = diffValue / hour,
        _min = diffValue / minute;

    var changeTime = new Date();
    changeTime.setTime(hisTime);

    var changeday = changeTime.getDate();
    var changemonth = changeTime.getMonth() + 1;
    var changeyear = changeTime.getFullYear();
    var changeHours = changeTime.getHours();

    var changeMinutes = changeTime.getMinutes();

    if (changeHours < 10) {
        changeHours = '0' + changeHours;
    }
    if (changeMinutes < 10) {
        changeMinutes = '0' + changeMinutes;
    }

    var d = new Date();
    var dd = d.getDate();
    var ddd = dd - changeday;
    // alert(ddd)
    if (ddd < 1) {
        if (_min <= 1) {
            result = '刚刚';
        } else if ((_min > 1) && (_hour < 1)) {
            result = parseInt(_min) + '分钟前';
        } else if ((_hour > 1) && (_day < 1)) {
            result = parseInt(_hour) + '小时前';
        }
    } else if (31 > ddd >= 1) {
        // result = changemonth + "-" + changeday;
        result = ddd + '天前';
    } else if (ddd >= 31) {
        result = changeyear + '-' + changemonth + '-' + changeday;
    }
    return result;
};

function changeImg(img) {

    if (img == null) {
        return '';
    }

    var arr = img.split(',') || '';

    return arr[0];

}

// 计算年龄
function timm(el) {
    var oldtime = new Date(el).getFullYear();
    var newtime = new Date().getFullYear();
    return newtime - oldtime;
}

//性别切换
function changeSex(index) {
    var aa = [
        '',
        '男',
        '女'];
    return aa[index];
}

/**
 *云之讯发送短信
 */
function setSMSCode(code4, phone, callBack) {

    //云之讯发送验证码
    smsVerification = api.require('smsVerification');
    smsVerification.sendMessage({
        softVersion: '2014-06-30',
        accountSid: '983def4ac6b7b08dfdffc2553c92088e',
        accountToken: 'e9b5105ca902bca5dac47f162afe9062',
        body: {
            appId: '0568650962be47c6bcfa8cd0ffabbb11',
            templateId: 186059,
            phoneNumber: phone, //输入的手机号
            param: code4 //验证码
        }
    }, function (ret) {

        console.log(code4 + '发送验证码' + JSON.stringify(ret));

        callBack(code4);

    });

}

/**
 *云之讯发送短信
 */
function setSMSCodeTest(phone, callBack) {

    //生成6位随机数
    var code4 = randomNmuber(0, 6);

    //云之讯发送验证码
    smsVerification = api.require('smsVerification');
    smsVerification.sendMessage({
        softVersion: '2017-08-23',
        accountSid: '983def4ac6b7b08dfdffc2553c92088e',
        accountToken: 'e9b5105ca902bca5dac47f162afe9062',
        body: {
            appId: '0568650962be47c6bcfa8cd0ffabbb11',
            templateId: 186059,
            phoneNumber: phone, //输入的手机号
            param: code4 //验证码
        }
    }, function (ret) {

        console.log(code4 + '发送验证码' + JSON.stringify(ret));

        callBack(code4);

    });

}

/*
 ** randomNmuber 产生任意长度随机数字
 ** randomFlag-是否任意长度 min-任意长度最小位[固定位数] max-任意长度最大位
 ** 生成3-32位随机串：randomNmuber(true, 3, 32)
 ** 生成43位随机串：randomNmuber(false, 43)
 */
function randomNmuber(randomFlag, min, max) {
    var str = '', range = min, arr = [
        '0',
        '1',
        '2',
        '3',
        '4',
        '5',
        '6',
        '7',
        '8',
        '9'];

    // 随机产生
    if (randomFlag) {
        range = Math.round(Math.random() * (max - min)) + min;
    }
    for (var i = 0; i < range; i++) {
        pos = Math.round(Math.random() * (arr.length - 1));
        str += arr[pos];
    }
    return str;
}

/////////////////////////////个推/////////////////////
/*
 *
 * 个推封装
 *
 */

function pushGeTui() {

    //个推初始化
    var uzgetuisdk = api.require('pushGeTui');
    uzgetuisdk.initialize(function (ret) {

        console.log('个推初始化：' + JSON.stringify(ret));

        var value = '';
        switch (ret.type) {
            case 'cid':
                value = 'cid:' + ret.cid;
                if (api.systemType == 'ios') {
                    registerDeviceToken(uzgetuisdk, ret.cid);
                }
                break;
            case 'payload':
                value = 'payload:' + ret.payload;

                console.warn('重新登录获取到上次透传过来的消息：' + JSON.stringify(ret));

                break;
            case 'occurError':
                value = 'occurError';
                break;
            case 'apns':

                console.warn('透传过来的信息：' + JSON.stringify(ret));

                break;

        }
    });

}

function registerDeviceToken(uzgetuisdk, cid) {

    var param = {
        deviceToken: api.deviceToken
    };
    uzgetuisdk.registerDeviceToken(param, function (ret, err) {
        console.log('注册个推成功返回：' + JSON.stringify(ret) + '||' + api.deviceToken);
    });
}

/*
 * 图片转换成getImgBase64
 * 例如：
 *
 * getImgBase64(ret.destPath,function(dataUrl){
   	console.log(dataUrl);
  	});
 *
 *
 */

function getImgBase64(path, callback) {
    var img = new Image();
    img.src = path;

    //图片加载完成后触发
    img.onload = function () {
        var canvas = document.createElement('canvas');
        //获取绘画上下文
        ctx = canvas.getContext('2d');

        // 获取图片宽高
        var imgWidth = img.width;
        var imgHeight = img.height;

        //设置画布宽高与图片宽高相同
        canvas.width = imgWidth;
        canvas.height = imgHeight;

        //绘制图片
        ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
        //图片展示的 data URI
        var dataUrl = canvas.toDataURL('image/png');
        callback ? callback(dataUrl) : '';
    };
}

//验证邮箱是否正确

function isEmail(str) {
    var reg = /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/;
    return reg.test(str);
}

/*
 *
 * 例子
var a = '1';
var arry = ['1', '2', '3', '4']
var index = indexOf(arry, a);
alert(index); // 弹出0
 *
 */
function indexOf(arr, str) {
    // 如果可以的话，调用原生方法
    if (arr && arr.indexOf) {
        return arr.indexOf(str);
    }

    var len = arr.length;
    for (var i = 0; i < len; i++) {
        // 定位该元素位置
        if (arr[i] == str) {
            return i;
        }
    }

    // 数组中不存在该元素
    return -1;
}

/*
 *
 * 例如：
 * 	 fnVisitor(function(data){

	 if(data){

	 //登录状态执行操作
	 var parame = {}
	 openWindow('mynews_win', './mynews_win.html', parame);
	 }

	 });
 *
 *
 *
 */

/*
 **
 **高德模块aMapLBS定位获取坐标
 */

function aMapLBSLocation(successFun, errorFun) {

    var aMapLBS = api.require('aMapLBS');
    aMapLBS.configManager({
        accuracy: 'tenMeters',
        filter: 1
    }, function (ret, err) {
        if (ret.status) {
            aMapLBS.singleLocation({
                timeout: 2
            }, function (ret, err) {

                if (ret.status) {

                    console.log('高德坐标' + JSON.stringify(ret));
                    successFun(ret);

                } else {

                    errorFun(err);
                    api.toast({
                        msg: '定位失败',
                        location: 'middle'
                    });
                }

            });
        }
    });

}

function aMapLBSAddress(successFun, errorFun) {

    var aMapLBS = api.require('aMapLBS');
    aMapLBS.configManager({
        accuracy: 'tenMeters',
        filter: 1
    }, function (ret, err) {
        if (ret.status) {
            aMapLBS.singleAddress({
                timeout: 2
            }, function (ret, err) {
                console.log('定位:' + JSON.stringify(ret));
                $api.setStorage('cityAddress', ret.address.city);
                if (ret.status) {
                    successFun(ret);
                } else {
                    errorFun(err);
                    api.toast({
                        msg: '定位失败',
                        location: 'middle'
                    });
                }
            });
        }
    });

}

//时间转换成时间戳
function getTimestamp(time) {

    var timeTamp = Date.parse(new Date(time.replace(/-/g, '/'))); //指定时间的毫秒数

    return timeTamp;

}

//时间戳转化成时间
function getDateTime(timeNumber, num) {
    var changeTime = new Date();
    changeTime.setTime(timeNumber);

    var changeday = changeTime.getDate();
    var changemonth = changeTime.getMonth() + 1;
    var changeyear = changeTime.getFullYear();
    var changeHours = changeTime.getHours();

    var changeMinutes = changeTime.getMinutes();
    if (num == 1) {

    } else {
        if (changemonth < 10) {
            changemonth = '0' + changemonth;
        }
        if (changeday < 10) {
            changeday = '0' + changeday;
        }
    }

    var result = changeyear + '-' + changemonth + '-' + changeday;

    return result;

}

//时间戳转化成时间
function getDateTime1(timeNumber) {
    var changeTime = new Date();
    changeTime.setTime(timeNumber);

    var changeday = changeTime.getDate();
    var changemonth = changeTime.getMonth() + 1;
    var changeyear = changeTime.getFullYear();
    var changeHours = changeTime.getHours();

    var changeMinutes = changeTime.getMinutes();

    if (changemonth < 10) {
        changemonth = '0' + changemonth;
    }
    if (changeday < 10) {
        changeday = '0' + changeday;
    }

    var result = changeyear + '-' + changemonth;

    return result;

}

/*
 *
 * 打开高德app导航
 *
 */

function openGaoDeAPP(lat, lon) {

    var navigator = api.require('navigator');

    navigator.installed({
        target: 'aMap'
    }, function (ret, err) {
        if (ret.status) {

            navigator.aMapNavigation({
                end: {
                    lon: lon,
                    lat: lat
                },
                dev: 0,
                strategy: 'fast'
            });

        } else {
            api.toast({
                msg: '未检测到高德app',
                duration: 2000,
                location: 'middle'
            });
        }
    });
}

/*
 *
 * 打开百度app导航
 *
 */

function openBaiDuAPP(lat, lon, mylat, mylon) {

    var navigator = api.require('navigator');

    navigator.installed({
        target: 'bMap'
    }, function (ret, err) {
        if (ret.status) {

            navigator.bMapNavigation({
                start: { // 起点信息.
                    lon: lon, // 经度.
                    lat: lat, // 纬度.
                    name: ''
                },
                end: { // 终点信息.
                    lon: mylon, // 经度
                    lat: mylat, // 纬度
                    name: ''
                },
                mode: 'driving'
            });

        } else {

            api.toast({
                msg: '未检测到百度app',
                duration: 2000,
                location: 'middle'
            });

        }
    });

}

//本项目的时间转换
function changeBenTime(hisTime, type) {

    if (hisTime == null) {
        hisTime = '1900-01-01 00:00:00';
    }
    date = hisTime.substring(0, 19);
    date = date.replace(/-/g, '/');

    hisTime = Date.parse(new Date(date)); //时间转时间搓

    var changeTime = new Date();
    changeTime.setTime(hisTime);

    var changeday = changeTime.getDate();
    var changemonth = changeTime.getMonth() + 1;
    var changeyear = changeTime.getFullYear();
    var changeHours = changeTime.getHours();

    var changeMinutes = changeTime.getMinutes();

    if (changemonth < 10) {
        changemonth = '0' + changemonth;
    }
    if (changeday < 10) {
        changeday = '0' + changeday;
    }

    if (changeHours < 10) {
        changeHours = '0' + changeHours;
    }
    if (changeMinutes < 10) {
        changeMinutes = '0' + changeMinutes;
    }

    if (type == 1) {
        var result = changemonth + '-' + changeday + ' ' + changeHours + ':' + changeMinutes;
    } else if (type == 2) {

        var result = changemonth + '月' + changeday + '日';

    } else {
        var result = changemonth + '月' + changeday + '日' + ' ' + changeHours + ':' + changeMinutes;
    }

    return result;

}

/**
 *
 * MD5 (Message-Digest Algorithm)
 * http://www.webtoolkit.info/
 *
 **/
var MD5 = function (string) {
    function RotateLeft(lValue, iShiftBits) {
        return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits));
    }

    function AddUnsigned(lX, lY) {
        var lX4, lY4, lX8, lY8, lResult;
        lX8 = (lX & 0x80000000);
        lY8 = (lY & 0x80000000);
        lX4 = (lX & 0x40000000);
        lY4 = (lY & 0x40000000);
        lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
        if (lX4 & lY4) {
            return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
        }
        if (lX4 | lY4) {
            if (lResult & 0x40000000) {
                return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
            } else {
                return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
            }
        } else {
            return (lResult ^ lX8 ^ lY8);
        }
    }

    function F(x, y, z) {
        return (x & y) | ((~x) & z);
    }

    function G(x, y, z) {
        return (x & z) | (y & (~z));
    }

    function H(x, y, z) {
        return (x ^ y ^ z);
    }

    function I(x, y, z) {
        return (y ^ (x | (~z)));
    }

    function FF(a, b, c, d, x, s, ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function GG(a, b, c, d, x, s, ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function HH(a, b, c, d, x, s, ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function II(a, b, c, d, x, s, ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function ConvertToWordArray(string) {
        var lWordCount;
        var lMessageLength = string.length;
        var lNumberOfWords_temp1 = lMessageLength + 8;
        var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64;
        var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16;
        var lWordArray = Array(lNumberOfWords - 1);
        var lBytePosition = 0;
        var lByteCount = 0;
        while (lByteCount < lMessageLength) {
            lWordCount = (lByteCount - (lByteCount % 4)) / 4;
            lBytePosition = (lByteCount % 4) * 8;
            lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition));
            lByteCount++;
        }
        lWordCount = (lByteCount - (lByteCount % 4)) / 4;
        lBytePosition = (lByteCount % 4) * 8;
        lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
        lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
        lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
        return lWordArray;
    };

    function WordToHex(lValue) {
        var WordToHexValue = '', WordToHexValue_temp = '', lByte, lCount;
        for (lCount = 0; lCount <= 3; lCount++) {
            lByte = (lValue >>> (lCount * 8)) & 255;
            WordToHexValue_temp = '0' + lByte.toString(16);
            WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length - 2, 2);
        }
        return WordToHexValue;
    };

    function Utf8Encode(string) {
        string = string.replace(/\r\n/g, '\n');
        var utftext = '';
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    };var x = Array();
    var k, AA, BB, CC, DD, a, b, c, d;
    var S11 = 7, S12 = 12, S13 = 17, S14 = 22;
    var S21 = 5, S22 = 9, S23 = 14, S24 = 20;
    var S31 = 4, S32 = 11, S33 = 16, S34 = 23;
    var S41 = 6, S42 = 10, S43 = 15, S44 = 21;
    string = Utf8Encode(string);
    x = ConvertToWordArray(string);
    a = 0x67452301;
    b = 0xEFCDAB89;
    c = 0x98BADCFE;
    d = 0x10325476;
    for (k = 0; k < x.length; k += 16) {
        AA = a;
        BB = b;
        CC = c;
        DD = d;
        a = FF(a, b, c, d, x[k + 0], S11, 0xD76AA478);
        d = FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756);
        c = FF(c, d, a, b, x[k + 2], S13, 0x242070DB);
        b = FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE);
        a = FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF);
        d = FF(d, a, b, c, x[k + 5], S12, 0x4787C62A);
        c = FF(c, d, a, b, x[k + 6], S13, 0xA8304613);
        b = FF(b, c, d, a, x[k + 7], S14, 0xFD469501);
        a = FF(a, b, c, d, x[k + 8], S11, 0x698098D8);
        d = FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF);
        c = FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1);
        b = FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE);
        a = FF(a, b, c, d, x[k + 12], S11, 0x6B901122);
        d = FF(d, a, b, c, x[k + 13], S12, 0xFD987193);
        c = FF(c, d, a, b, x[k + 14], S13, 0xA679438E);
        b = FF(b, c, d, a, x[k + 15], S14, 0x49B40821);
        a = GG(a, b, c, d, x[k + 1], S21, 0xF61E2562);
        d = GG(d, a, b, c, x[k + 6], S22, 0xC040B340);
        c = GG(c, d, a, b, x[k + 11], S23, 0x265E5A51);
        b = GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA);
        a = GG(a, b, c, d, x[k + 5], S21, 0xD62F105D);
        d = GG(d, a, b, c, x[k + 10], S22, 0x2441453);
        c = GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681);
        b = GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8);
        a = GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6);
        d = GG(d, a, b, c, x[k + 14], S22, 0xC33707D6);
        c = GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87);
        b = GG(b, c, d, a, x[k + 8], S24, 0x455A14ED);
        a = GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905);
        d = GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8);
        c = GG(c, d, a, b, x[k + 7], S23, 0x676F02D9);
        b = GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A);
        a = HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942);
        d = HH(d, a, b, c, x[k + 8], S32, 0x8771F681);
        c = HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122);
        b = HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C);
        a = HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44);
        d = HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9);
        c = HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60);
        b = HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70);
        a = HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6);
        d = HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA);
        c = HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085);
        b = HH(b, c, d, a, x[k + 6], S34, 0x4881D05);
        a = HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039);
        d = HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5);
        c = HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8);
        b = HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665);
        a = II(a, b, c, d, x[k + 0], S41, 0xF4292244);
        d = II(d, a, b, c, x[k + 7], S42, 0x432AFF97);
        c = II(c, d, a, b, x[k + 14], S43, 0xAB9423A7);
        b = II(b, c, d, a, x[k + 5], S44, 0xFC93A039);
        a = II(a, b, c, d, x[k + 12], S41, 0x655B59C3);
        d = II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92);
        c = II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D);
        b = II(b, c, d, a, x[k + 1], S44, 0x85845DD1);
        a = II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F);
        d = II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0);
        c = II(c, d, a, b, x[k + 6], S43, 0xA3014314);
        b = II(b, c, d, a, x[k + 13], S44, 0x4E0811A1);
        a = II(a, b, c, d, x[k + 4], S41, 0xF7537E82);
        d = II(d, a, b, c, x[k + 11], S42, 0xBD3AF235);
        c = II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB);
        b = II(b, c, d, a, x[k + 9], S44, 0xEB86D391);
        a = AddUnsigned(a, AA);
        b = AddUnsigned(b, BB);
        c = AddUnsigned(c, CC);
        d = AddUnsigned(d, DD);
    }
    var temp = WordToHex(a) + WordToHex(b) + WordToHex(c) + WordToHex(d);
    return temp.toLowerCase();
};

/**
 * Created by andy on 14-12-25.
 */
/**
 *
 *  Secure Hash Algorithm (SHA1)
 *  http://www.webtoolkit.info/
 *
 **/

function SHA1(msg) {

    function rotate_left(n, s) {
        var t4 = (n << s) | (n >>> (32 - s));
        return t4;
    };

    function lsb_hex(val) {
        var str = '';
        var i;
        var vh;
        var vl;

        for (i = 0; i <= 6; i += 2) {
            vh = (val >>> (i * 4 + 4)) & 0x0f;
            vl = (val >>> (i * 4)) & 0x0f;
            str += vh.toString(16) + vl.toString(16);
        }
        return str;
    };

    function cvt_hex(val) {
        var str = '';
        var i;
        var v;

        for (i = 7; i >= 0; i--) {
            v = (val >>> (i * 4)) & 0x0f;
            str += v.toString(16);
        }
        return str;
    };

    function Utf8Encode(string) {
        string = string.replace(/\r\n/g, '\n');
        var utftext = '';

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    };

    var blockstart;
    var i, j;
    var W = new Array(80);
    var H0 = 0x67452301;
    var H1 = 0xEFCDAB89;
    var H2 = 0x98BADCFE;
    var H3 = 0x10325476;
    var H4 = 0xC3D2E1F0;
    var A, B, C, D, E;
    var temp;

    msg = Utf8Encode(msg);

    var msg_len = msg.length;

    var word_array = new Array();
    for (i = 0; i < msg_len - 3; i += 4) {
        j = msg.charCodeAt(i) << 24 | msg.charCodeAt(i + 1) << 16 | msg.charCodeAt(i + 2) << 8 | msg.charCodeAt(i + 3);
        word_array.push(j);
    }

    switch (msg_len % 4) {
        case 0:
            i = 0x080000000;
            break;
        case 1:
            i = msg.charCodeAt(msg_len - 1) << 24 | 0x0800000;
            break;

        case 2:
            i = msg.charCodeAt(msg_len - 2) << 24 | msg.charCodeAt(msg_len - 1) << 16 | 0x08000;
            break;

        case 3:
            i = msg.charCodeAt(msg_len - 3) << 24 | msg.charCodeAt(msg_len - 2) << 16 | msg.charCodeAt(msg_len - 1) << 8 | 0x80;
            break;
    }

    word_array.push(i);

    while ((word_array.length % 16) != 14) word_array.push(0);

    word_array.push(msg_len >>> 29);
    word_array.push((msg_len << 3) & 0x0ffffffff);

    for (blockstart = 0; blockstart < word_array.length; blockstart += 16) {

        for (i = 0; i < 16; i++) W[i] = word_array[blockstart + i];
        for (i = 16; i <= 79; i++) W[i] = rotate_left(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);

        A = H0;
        B = H1;
        C = H2;
        D = H3;
        E = H4;

        for (i = 0; i <= 19; i++) {
            temp = (rotate_left(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B, 30);
            B = A;
            A = temp;
        }

        for (i = 20; i <= 39; i++) {
            temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B, 30);
            B = A;
            A = temp;
        }

        for (i = 40; i <= 59; i++) {
            temp = (rotate_left(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B, 30);
            B = A;
            A = temp;
        }

        for (i = 60; i <= 79; i++) {
            temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B, 30);
            B = A;
            A = temp;
        }

        H0 = (H0 + A) & 0x0ffffffff;
        H1 = (H1 + B) & 0x0ffffffff;
        H2 = (H2 + C) & 0x0ffffffff;
        H3 = (H3 + D) & 0x0ffffffff;
        H4 = (H4 + E) & 0x0ffffffff;

    }

    var temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4);

    return temp.toLowerCase();

}

//////////////////////////////////////////////md5////////////////

/////////////////////////////////极光推送逻辑/////////////////////////

//绑定极光
function tooAjpush() {

    var ajpush = api.require('ajpush');

    if (api.systemType == 'ios') {
        var param = {
            alias: $api.getStorage('allUser').user_id
        };

        ajpush.bindAliasAndTags(param, function (ret) {

            var statusCode = ret.statusCode;

            console.log('绑定别名成功' + statusCode + '||' + $api.getStorage('allUser').user_id);
            if (statusCode == 6002) {
                tooAjpush();
            }
            setListenerAjpush();
            setListenerAjpushIos();
        });
    } else {
        ajpush.init(function (ret) {
            if (ret && ret.status) {
                var param = {
                    alias: $api.getStorage('allUser').user_id
                };
                ajpush.bindAliasAndTags(param, function (ret) {
                    var statusCode = ret.statusCode;
                    console.log('绑定别名返回状态' + statusCode + '||' + $api.getStorage('allUser').user_id);
                    if (statusCode == 6002) {
                        tooAjpush();
                    }
                    setListenerAjpush();
                    setListenerAjpushAndor();

                });
            }
        });

    }
}

//1(订单消息，包括：收货和发货) 2(系统消息) 3(设备锁消息（开锁，关锁）)4(监控信息)
//监听通知以及消息
function setListenerAjpush() {

    var ajpush = api.require('ajpush');
    ajpush.setListener(function (ret) {
        var id = ret.id;
        var title = ret.title;
        var content = ret.content;
        var extra = ret.extra;
        var issss = extra._j_business || '';

        console.log(JSON.stringify(ret) + '||监听推送');
        var jsfun = 'initData();';
        api.execScript({
            name: 'root1',
            frameName: 'main1_frm',
            script: jsfun
        });

        if (extra != '' && issss == '') {

            if (extra.extra != {} || extra.extra != '{}') {

                var getextra = eval('(' + extra.extra + ')');


            }

        }

    });

}

//通知被点击安卓
function setListenerAjpushAndor() {
    api.addEventListener({
        name: 'appintent'
    }, function (ret, err) {
        if (ret && ret.appParam.ajpush) {
            var ajpush = ret.appParam.ajpush;
            var id = ajpush.id;
            var title = ajpush.title;
            var content = ajpush.content;
            var extra = JSON.parse(ajpush.extra.extra);
            //alert(JSON.stringify(ret));

        } else {
            console.log(JSON.stringify(ret));
        }
    });

}

//通知被点击ios
function setListenerAjpushIos() {

    api.addEventListener({
        name: 'noticeclicked'
    }, function (ret, err) {
        console.log(JSON.stringify(ret) + '|||||||ios点击:');
        if (ret && ret.value) {
            var ajpush = ret.value;
            var content = ajpush.content;
            var extra = ajpush.extra;
            var extra = JSON.parse(extra);

        } else {
            console.log(JSON.stringify(ret));
        }
    });

}

////////////////////支付前台自己发起支付///////////////////

//微信支付
function payWX() {

    var wxPay = api.require('wxPay');
    wxPay.config({
        apiKey: '',
        mchId: '',
        partnerKey: '',
        notifyUrl: ''
    }, function (ret, err) {
        if (ret.status) {

            console.log('配置key正确' + JSON.stringify(ret));

            var nonono = randomWord(false, 30);

            wxPay.pay({
                description: 'hello:测试测试',
                totalFee: '1',
                tradeNo: nonono
            }, function (ret, err) {

                console.log('支付正确正确....' + JSON.stringify(ret) + '支付错误错误....' + JSON.stringify(err));
                if (ret.status) {
                    //alert(ret.result);
                } else {
                    //alert(err.code);
                }
            });

        } else {
            alert(JSON.stringify(err));
        }
    });

}

//支付宝支付
function payZF() {

    var aliPayPlus = api.require('aliPayPlus');
    aliPayPlus.config({
        appId: '',
        rsaPriKey:'',
    }, function (ret, err) {

        var nonono = randomWord(false, 30);

        aliPayPlus.pay({
            subject: '订单名',
            body: '订单描述',
            amount: '0.01',
            tradeNO: nonono,
            rsa2: true
        }, function (ret, err) {
            api.alert({
                title: '支付结果',
                msg: JSON.stringify(ret),
                buttons: ['确定']
            });
        });

    });

}

function aMapLBSAddress(successFun, errorFun) {

    var aMapLBS = api.require('aMapLBS');
    aMapLBS.configManager({
        accuracy: 'tenMeters',
        filter: 1
    }, function (ret, err) {
        if (ret.status) {
            aMapLBS.singleAddress({
                timeout: 2
            }, function (ret, err) {
                console.log('定位:' + JSON.stringify(ret));

                if (ret.status) {
                    successFun(ret);
                    $api.setStorage('cityAddress', ret.address.city);
                } else {
                    errorFun(err);
                    api.toast({
                        msg: '定位失败',
                        location: 'middle'
                    });
                }
            });
        }
    });

}

//////////////////////后台发起支付/////////////////

/////////////////////////微信////////////////////////
/*	例子：
	var data = {
	}
	payServerWX(data,function(successData) {
	//成功回调执行函数
	}, function(errorData) {
	//失败回调执行函数
	})
*/

function payServerWX(data, successFun, errorFun) {

    var wxPay = api.require('wxPay');
    wxPay.payOrder({
        apiKey: 'wx873fd2770ec00031',
        orderId: data.prepayid, //prepayid
        mchId: '1507731581',
        nonceStr: data.noncestr, //noncestr
        timeStamp: data.timestamp, //timestamp
        package: 'Sign=WXPay',
        sign: data.sign //sign
    }, function (ret, err) {
        if (ret.status) {
            console.log(JSON.stringify(ret) + '支付成功返回参数');
            successFun(ret);
        } else {
            console.log(err.code + '支付失败跳转返回参数');
            errorFun(err);
            return;
        }
    });

}

/*	例子：
	var data = {
	}
	payServerZFB(data,function(successData) {
	//成功回调执行函数
	}, function(errorData) {
	//失败回调执行函数
	})
*/

////////////////////支付宝//////////////////

function payServerZFB(data, successFun, errorFun) {

    //打开支付宝支付
    var aliPayPlus = api.require('aliPayPlus');
    aliPayPlus.payOrder({
        orderInfo: data.data.orderInfo
    }, function (ret, err) {

        console.log(JSON.stringify(ret) + '||' + JSON.stringify(err));

        if (ret.statusCode == '9000') {

            console.log(JSON.stringify(ret) + '支付成功返回参数');
            successFun(ret);

        } else {

            console.log(JSON.stringify(err) + '支付失败返回参数');
            errorFun(err);
            return;

        }
    });

}

/*
 ** randomWord 产生任意长度随机字母数字组合
 ** randomFlag-是否任意长度 min-任意长度最小位[固定位数] max-任意长度最大位
 ** 生成3-32位随机串：randomWord(true, 3, 32)
 ** 生成43位随机串：randomWord(false, 43)
 */

function randomWord(randomFlag, min, max) {
    var str = '', range = min, arr = [
        '0',
        '1',
        '2',
        '3',
        '4',
        '5',
        '6',
        '7',
        '8',
        '9',
        'a',
        'b',
        'c',
        'd',
        'e',
        'f',
        'g',
        'h',
        'i',
        'j',
        'k',
        'l',
        'm',
        'n',
        'o',
        'p',
        'q',
        'r',
        's',
        't',
        'u',
        'v',
        'w',
        'x',
        'y',
        'z',
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z'];

    // 随机产生
    if (randomFlag) {
        range = Math.round(Math.random() * (max - min)) + min;
    }
    for (var i = 0; i < range; i++) {
        pos = Math.round(Math.random() * (arr.length - 1));
        str += arr[pos];
    }
    return str;
}

/**
 *
 * 打开相册
 *
 *  openCamera(0,function(url){
 *  });
 *
 *
 */

function openCamera(type, sucessFun) {

    var typeArray = [
        'camera',
        'album'];

    api.getPicture({
        sourceType: typeArray[type],
        encodingType: 'png',
        mediaValue: 'pic',
        destinationType: 'url',
        allowEdit: false,
        quality: 80,
        saveToPhotoAlbum: true
    }, function (ret, err) {

        console.log('打开摄像机返回的数据' + JSON.stringify(ret));

        if (ret && ret.data != '') {

            var dataImg = ret.data;
            return sucessFun(dataImg);

        } else {
            //alert(JSON.stringify(err));
        }
    });

}

/**
 *
 * 压缩单张图片
 *
 */

function yasuo(dataImg, successFun) {

    LoadingShow();
    var imageFilter = api.require('imageFilter');
    var imgName = 'clue_picture_' + Math.random() + '.jpg';
    imageFilter.compress({
        img: dataImg,
        quality: 0.8,
        scale: 1,
        save: {
            album: false,
            imgPath: 'fs://clue/',
            imgName: imgName
        }
    }, function (ret, err) {

        LoadingClose();
        var path = ret.status ? api.fsDir + '/clue/' + imgName :

            [i];
        console.log('压缩图片！！！' + JSON.stringify(ret) + '路径' + path);
        //调用上传头像的接口

        successFun(path);

    });
}

/**
 *
 * 压缩多张图片
 *
 */
var yaSuoImgggg = [];

function yasuoImgs(all, index, successFun) {
    if (index == 0) {
        yaSuoImgggg = [];
    }
    var imageFilter = api.require('imageFilter');
    LoadingShow();
    console.log('赫尔' + all.length + '||' + index);
    if (all.length <= index) {

        LoadingClose();
        //完成执行的方法
        console.log('缓存完成!!!' + JSON.stringify(yaSuoImgggg));

        return successFun(yaSuoImgggg);

    }

    if (api.systemType == 'ios') {

        var UIMediaScanner = api.require('UIMediaScanner');
        UIMediaScanner.transPath({
            path: all[index].path
        }, function (ret, err) {
            if (ret) {

                var imgName = 'clue_picture_' + Math.random() + '.jpg';
                imageFilter.compress({
                    img: ret.path,
                    quality: 0.8,
                    scale: 1,
                    save: {
                        album: false,
                        imgPath: 'fs://clue/',
                        imgName: imgName
                    }
                }, function (ret, err) {

                    var path = ret.status ? api.fsDir + '/clue/' + imgName : images[i];
                    console.log('压缩图片！！！' + JSON.stringify(ret) + '路径' + path);
                    //调用上传头像的接口
                    yaSuoImgggg.push(path);
                    yasuoImgs(all, index + 1, successFun);

                });

            } else {
                alert(JSON.stringify(err));
            }
        });

    } else {

        var imgName = 'clue_picture_' + Math.random() + '.jpg';
        imageFilter.compress({
            img: all[index].path,
            quality: 0.8,
            scale: 1,
            save: {
                album: false,
                imgPath: 'fs://clue/',
                imgName: imgName
            }
        }, function (ret, err) {
            //         alert("数据解决"+JSON.stringify(ret))

            var path = ret.status ? api.fsDir + '/clue/' + imgName : images[i];
            console.log('压缩图片！！！' + JSON.stringify(ret) + '路径' + path);
            //调用上传头像的接口
            yaSuoImgggg.push(path);
            yasuoImgs(all, index + 1, successFun);

        });

    }

}

/**
 *
 * 打开图片多张
 *
 */

function openAlbum(maxNumber, successFun) {

    var UIMediaScanner = api.require('UIMediaScanner');
    UIMediaScanner.open({
        type: 'picture',
        column: 4,
        classify: false,
        max: maxNumber,
        sort: {
            key: 'time',
            order: 'desc'
        },
        texts: {
            stateText: '已选择*项',
            cancelText: '取消',
            finishText: '完成'
        },
        styles: {
            bg: '#fff',
            mark: {
                icon: '',
                position: 'bottom_left',
                size: 20
            },
            nav: {
                bg: '#eee',
                stateColor: '#000',
                stateSize: 18,
                cancelBg: 'rgba(0,0,0,0)',
                cancelColor: '#000',
                cancelSize: 18,
                finishBg: 'rgba(0,0,0,0)',
                finishColor: '#000',
                finishSize: 18
            }
        },
        scrollToBottom: {
            intervalTime: -1,
            anim: true
        },
        exchange: true,
        rotation: true
    }, function (ret) {
        if (ret) {

            if (ret.eventType == 'confirm') {
                console.log('打开多张图片' + JSON.stringify(ret));
                successFun(ret);
            }

        }
    });

}

// 放大图片不传值
function showBigPicture0(picArr, index) {
    console.log('图片图片！！' + picArr);
    var photoBrowser = api.require('photoBrowser');
    photoBrowser.open({
        images: picArr,
        activeIndex: index,
        placeholderImg: 'widget://res/img/apicloud.png',
        bgColor: '#000'
    }, function (ret, err) {
        if (ret) {
            console.log(JSON.stringify(ret));
            var indexx = ret.index;
            if (ret.eventType == 'click') {
                photoBrowser.close();
            }
            // else if(ret.eventType == "show"){
            //
            // }else if(ret.eventType=='change'){
            //
            // }
        } else {
            //alert(JSON.stringify(err));
        }
    });
}

function showBigPicture(picArr, index, message) {

    console.log('图片图片！！' + picArr);

    var photoBrowser = api.require('photoBrowser');
    photoBrowser.open({
        images: picArr,
        activeIndex: index,
        placeholderImg: 'widget://res/img/apicloud.png',
        bgColor: '#fff'
    }, function (ret, err) {
        if (ret) {
            console.log(JSON.stringify(ret));
            var indexx = ret.index;
            if (ret.eventType == 'click') {
                photoBrowser.close();

                api.closeFrame({
                    name: 'big_pic_win'
                });

            } else if (ret.eventType == 'show') {

                api.openFrame({
                    name: 'big_pic_win',
                    url: '../main2/big_pic_win.html',
                    rect: {
                        x: 0,
                        y: api.winHeight - 150,
                        w: 'auto',
                        h: 'auto'
                    },
                    pageParam: {
                        index: index,
                        message: message
                    },
                    bounces: false
                });

            } else if (ret.eventType == 'change') {

                var jsfun = 'getWhere("' + ret.index + '");';
                api.execScript({
                    name: 'organization_win',
                    frameName: 'big_pic_win',
                    script: jsfun
                });

            }

        } else {
            //alert(JSON.stringify(err));
        }
    });

}

function showBigPicture1(picArr, index) {

    console.log('图片图片！！' + picArr);

    var photoBrowser = api.require('photoBrowser');
    photoBrowser.open({
        images: picArr,
        activeIndex: index,
        placeholderImg: 'widget://res/img/apicloud.png',
        bgColor: '#fff'
    }, function (ret, err) {
        if (ret) {
            console.log(JSON.stringify(ret));
            if (ret.eventType == 'click') {
                photoBrowser.close();
            }

        } else {
            //alert(JSON.stringify(err));
        }
    });

}

/**
 *
 * 同步缓存多张图片到本地
 * saveToLoaclImg('数组数据',0);
 */

var shuzu = [];

function saveToLoaclImg(all, index, successFun) {

    LoadingShow();

    if (all) {

        if (all.length <= index) {

            LoadingClose();
            //完成执行的方法
            console.log('缓存完成!!!' + JSON.stringify(shuzu));

            successFun(shuzu);
            return;

        }

        api.imageCache({
            url: all[index],
            encode: false,
            policy: 'cache_else_network',
            thumbnail: false
        }, function (ret, err) {

            console.log(JSON.stringify(all) + '缓存图片' + JSON.stringify(ret) + '|||' + JSON.stringify(err) + '|||');

            shuzu.push(ret.url);
            saveToLoaclImg(all, index + 1, successFun);
        });
    }
}

/**
 *
 * 同步一张图片到本地
 * saveToLoaclImgOne('图片地址',successFun);
 */


function saveToLoaclImgOne(img, successFun) {

    //var aaa=[];
    //aaa.push('/var/mobile/Containers/Data/Application/C115EF46-8D72-42BD-BCC5-A574CCAC2B00/Library/Caches/APICloud/Cache/45e891085af2b9b579164c6c73da1c9f_thumb.png');
    //
    //var compactPicture = api.require('compactPicture');
    //compactPicture.HittingPic({
    //  picpatharray: aaa,
    //  size: 1
    //}, function(ret) {
    //
    //	console.log(ret.states[0]);
    //
    //var imageFilter = api.require('imageFilter');
    //imageFilter.getAttr({
    //  path:ret.states[0]
    //},function( ret, err ){
    //  if( ret.status ){
    //      alert( JSON.stringify( ret ) );
    //  }else{
    //      alert( JSON.stringify( err ) );
    //  }
    //});
    //
    //
    //});
    //
    //return;

    if (img == '' || img == null) {
        successFun('../../image/zanweitu/book2.png');
        return;
    }

    LoadingShow();
    api.imageCache({
        url: img,
        encode: false,
        policy: 'cache_else_network',
        thumbnail: false
    }, function (ret, err) {
        LoadingClose();
        console.log('缓存图片' + JSON.stringify(ret) + '|||' + JSON.stringify(err) + '|||');

        if (err) {
            successFun('../../image/zanweitu/book2.png');
        } else {

            // if (api.systemType == 'ios') {
            //
            //   var compactPicture = api.require('compactPicture');
            //   compactPicture.HittingPic({
            //     picpatharray: [ret.url],
            //     size: 3
            //   }, function (ret) {
            //     // alert(JSON.stringify(ret));
            //     successFun(ret.states[0]);
            //
            //   });
            //
            // } else {
            successFun(ret.url);
            // }

            //console.log(ret.url);
            //var imageFilter = api.require('imageFilter');
            //imageFilter.getAttr({
            //  path: ret.url
            //},function( ret, err ){
            //  if( ret.status ){
            //      alert( JSON.stringify( ret ) );
            //  }else{
            //      alert( JSON.stringify( err ) );
            //  }
            //});
            //
            //alert(ret.url);
            //console.log(ret.url);
            //return;

        }

    });

}

function countDownTime(time1, time2) {

    //alert(timetrans(time1)+"|||||"+timetrans(time2));

    var time = Number(time1) + 1800000 - Number(time2);

    if (time > 0) {

        //时间转换成秒
        var newMinutes = parseInt(time / 60000);
        //小时
        var newHours = parseInt(newMinutes / 60);
        //分钟
        newMinutes = newMinutes - newHours * 60;

        return '剩余:' + newMinutes + '分钟';
    } else {
        return '订单失效';
    }

}

//一天之内显示时分秒，一月之内显示月日，一年之内显示年月日
function timetranss(date) {
    var date = new Date(date); //如果date为10位不需要乘1000
    var date_new = new Date();
    var s_fan = date.getTime();
    var s_all = date_new.getTime();

    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
    var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
    if ((s_all - s_fan) < 86400000) {
        return h + m + s;
    } else if ((s_all - s_fan) < (86400000 * 30)) {
        return M + D;
    } else {
        return Y + M + D;
    }
}

//时间搓 转时间
function timetrans(date) {
    var date = new Date(date); //如果date为10位不需要乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
    var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
    return Y + M + D + h + m + s;
}

//返回天数
function countDownTime2(time) {

    if (time > 0) {
        //时间转换成分
        var newMinutes = parseInt(time / 60000);

        //小时
        var newHours = parseInt(newMinutes / 60);

        var newDays = parseInt(newMinutes / 1440);

        var bHours = newHours - newDays * 24;

        return '剩余:' + newDays + '天' + bHours + '小时';

    } else {
        return '已逾期';
    }

}

///手机号//
function fnPhone(phonee) {
    var phone = phonee.substring(0, 3) + '****' + phonee.substring(7, 11);
    return phone;
}

//计算折扣
function discount(max, min) {

    if (max == 0) {
        return '0折';
    }
    var max = max || 0;
    var min = min || 0;
    var zheke = (min / max).toFixed(2);
    //console.log(max+"|||"+min+"||"+zheke);
    return zheke * 10 + '折';
}

/**
 *
 *db模块
 *
 *全部
 *
 */


////打开db
//function openDataBase() {
//
//  var db = api.require('db');
//  db.openDatabase({
//      name: 'foot'
//  }, function(ret, err) {
//
//      creatMyDB(); //新建一个表用来存足迹数据
//
//  });
//}
//
//
////全部全部全部
//function creatMyDB() {
//
//  var userId = $api.getStorage('userId');
//  var bdName = 'a' + userId;
//
//  var sql = "CREATE TABLE'" + bdName + "'(id varchar(255),type varchar(255),createtime varchar(255),other varchar(255))";
//
//  //更新SQL
//  upDataSql(sql, function() {
//      //
//  });
//
//}

//执行SQL
function upDataSql(sql, fun) {
    console.log('新增SQL!!!!!' + sql);
    var db = api.require('db');
    db.executeSql({
        name: 'msg',
        sql: sql
    }, function (ret, err) {
        if (ret.status) {
            fun(ret.status);
            console.log('第一次进入app新建聊天表成功！！！！and！！！新增条数返回状态||||' + JSON.stringify(ret));
        } else {
            console.log(JSON.stringify(err.msg));
        }
    });
}

/*
 * 	查询SQL

	var userId = $api.getStorage('userId');
	var bdName='a'+userId;
	readSQL('SELECT * FROM "'+ bdName +'" ORDER BY createtime DESC', function(succData) {

	alert(JSON.stringify(succData));
	});
 */
function readSQL(sql, fun) {
    var db = api.require('db');
    db.selectSql({
        name: 'msg',
        sql: sql
    }, function (ret, err) {
        if (ret.status) {

            //console.log("查询表返回数据"+JSON.stringify(ret));
            var data = ret.data;
            fun(data);
        } else {
            console.log(JSON.stringify(err));
            //api.({
            //	"title" : "提示",
            //	"msg" : "数据查询失败"
            //}, function(ret, err) {
            //});
        }
    });
}

/*
 *
 *	删除表
 * 	delectSql(function(){

	});
 *
 */

function delectSql(fun) {

    var userId = $api.getStorage('userId');
    var bdName = 'a' + userId;

    var db = api.require('db');
    db.executeSql({
        name: 'foot',
        sql: 'DELETE FROM ' + bdName
    }, function (ret, err) {
        if (ret.status) {
            fun(ret.status);
        } else {
            console.log(JSON.stringify(err.msg));
        }
    });
}

/*
 * 往本地添加一条是数据
 */

function saveLocal(idd, type) {
    var userId = $api.getStorage('userId');
    var bdName = 'a' + userId;
    var timestamp = Date.parse(new Date());

    //获得的idd
    //执行查询语句，如果有数据不添加。否则新增一条

    readSQL('SELECT * FROM "' + bdName + '" where id="' + idd + '"', function (succData) {

        console.log('插入的时候查看时候有相同的数据：' + JSON.stringify(succData));

        if (succData.length == 0) {

            var sql = 'INSERT INTO \'' + bdName + '\'(id,type,createtime)';
            sql = sql + 'VALUES (\'' + idd + '\',\'' + type + '\',\'' + timestamp + '\')';

            upDataSql(sql, function () {
                console.log('没有相同的数据插入成功一条！！！');
            });

        }

    });

}

//////////////////////////////////超级团队 /////////////////
var convertFullDateTime = function (date) {
    var date = new Date();
    date.setTime(date);
    return date.Format('yyyy-MM-dd hh:mm:ss');
};

var convertFullDateTime2 = function (data) {
    var date = new Date();
    date.setTime(data);
    return date.Format('yyyy-MM-dd hh:mm');
};

Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        'M+': this.getMonth() + 1, //月份
        'd+': this.getDate(), //日
        'h+': this.getHours(), //小时
        'm+': this.getMinutes(), //分
        's+': this.getSeconds(), //秒
        'q+': Math.floor((this.getMonth() + 3) / 3), //季度
        'S': this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    for (var k in o) if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
    return fmt;
};

function isFirst(funs) {
    var isFirst = $api.getStorage('isFirst') || '';

    var db = api.require('db');
    if (isFirst == '') {
        //首次加载创建数据库

        db.openDatabase({
            name: 'msg'
        }, function (ret, err) {
            if (ret.status) {

                var sql = 'CREATE TABLE msg(duration varchar(255),contentextra varchar(111)  DEFAULT NULL,contenttext varchar(111) DEFAULT NULL, conversationType varchar(111) DEFAULT NULL, extra varchar(2000) DEFAULT NULL,messageDirection varchar(111) DEFAULT NULL, messageid varchar(111) NOT NULL, objectname varchar(111) DEFAULT NULL,receivedtime varchar(111) DEFAULT NULL, senderuserid varchar(111) DEFAULT NULL, sendstatus varchar(111) DEFAULT NULL, sendtime varchar(111) DEFAULT NULL,targetid varchar(111) DEFAULT NULL, userid varchar(111) DEFAULT NULL, createtime varchar(111) DEFAULT NULL,status varchar(111) DEFAULT NULL,other1 varchar(111) DEFAULT NULL,other2 varchar(111) DEFAULT NULL,other3 varchar(111) DEFAULT NULL,poi varchar(111) DEFAULT NULL,latitude varchar(111) DEFAULT NULL,longitude varchar(111) DEFAULT NULL)';

                //更新SQL
                upDataSql(sql, function () {
                    //
                });

            } else {
                api.toast({
                    msg: '系统初始化失败'
                });
            }
        });
    } else {
        db.openDatabase({
            name: 'msg'
        }, function (ret, err) {
            funs();
            console.log('不是第一次进入app打开数据库成功！！！！' + JSON.stringify(ret));
            //			api.execScript({
            //				script : 'initMessage();',
            //				name : "root"
            //			});
        });
    }

    $api.setStorage('isFirst', 'isFirst');

}

//////////////////初始化融云//////////////////
//
// function initRongYun() {
//   var rongCloud2 = api.require('rongCloud2');
//
//   rongCloud2.init(function (ret, err) {
//     if (ret.status == 'error') {
//       api.toast({
//         msg: err.code
//       });
//     }
//
//     var rongToken = $api.getStorage('allUser').rytoken;
//
//     rongCloud2.setOnReceiveMessageListener(function (ret, err) {
//
//       console.log('融云返回！！！！message ' + JSON.stringify(ret.result.message));
//       var extra = ret.result.message.content.extra || '';
//       console.warn(extra + 'aa');
//       var conversationType = ret.result.message.conversationType;
//       var targetId = ret.result.message.targetId;
//
//       rongCloud2.setConversationNotificationStatus({
//         conversationType: conversationType,
//         targetId: targetId,
//         notificationStatus: 'DO_NOT_DISTURB'
//       }, function (ret, err) {
//         if (ret.status == 'success') {
//           // d.resolve(ret);
//         } else {
//           err.where = 'rong.setConversationNotificationStatus 1';
//           //d.reject(err);
//         }
//       });
//
//       //监听到发送信息保存
//       saveMessage(ret.result.message);
//
//       //          if (extra != "" && extra.indexOf("REPORT") >= 0) {
//       //              //显示报道的小红点
//       //              api.execScript({
//       //                  script: 'baodao(1);',
//       //                  name: "root"
//       //              });
//       //          } else if (extra != "" && extra.indexOf("NEWS") >= 0) {
//       //              api.execScript({
//       //                  script: 'baodao(0);',
//       //                  name: "root"
//       //              });
//       //          } else {
//       //              saveMessage(ret.result.message);
//       //          }
//
//     });
//
//     rongCloud2.setConnectionStatusListener(function (ret, err) {
//       var status = ret.result.connectionStatus;
//       if (status == 'KICKED') {
//         $api.rmStorage('allUser');
//
//         api.alert({
//           msg: '您的账号已在其他设备登陆'
//         }, function (ret, err) {
//           //coding...
//           api.rebootApp();
//
//         });
//
//       }
//     });
//
//     rongCloud2.connect({
//       token: rongToken
//     }, function (ret, err) {
//       console.warn('链接融云返回参数' + JSON.stringify(ret) + '||||失败码：' + JSON.stringify(err));
//       //          initMessage();
//     });
//
//   });
//
//   api.addEventListener({
//     name: 'noticeclicked'
//   }, function (ret, err) {
//
//   });
// }
//
// var saveMessage = function (message) {
//   var contentextra = message.content.extra;
//   var contenttext = message.content.text;
//   var conversationType = message.conversationType;
//
//   var extra = message.extra;
//   var messageDirection = message.messageDirection;
//   var messageId = message.messageId;
//   var objectName = message.objectName;
//   var receivedTime = message.receivedTime;
//   var senderUserId = message.senderUserId;
//   var sentStatus = message.sentStatus;
//   var sentTime = message.sentTime;
//   var duration = message.duration || '';
//   var targetId = message.targetId || '';
//   var userId = $api.getStorage('allUser').user_id;
//
//   var poi = '';
//   var latitude = '';
//   var longitude = '';
//
//   if (openChatWindow == false) {
//     console.warn(conversationType);
//     if (conversationType == 'PRIVATE') {
//       console.log(senderUserId);
//
//       var isRemind = $api.getStorage('isOpen_' + userId) || '';
//
//       if (isRemind == '') {
//         api.notification({
//           notify: {
//             content: '你收到了一条信息',
//             title: '爱犬'
//           }
//         }, function (ret, err) {
//         });
//       }
//       var rongCloud2 = api.require('rongCloud2');
//
//       rongCloud2.setConversationNotificationStatus({
//         conversationType: conversationType,
//         targetId: targetId,
//         notificationStatus: 'NOTIFY'
//       }, function (ret, err) {
//         if (ret.status == 'success') {
//           console.log('-----------------');
//         } else {
//           err.where = 'rong.setConversationNotificationStatus 1';
//           //			        d.reject(err);
//         }
//       });
//
//       //			var name = $api.getStorage("name" + senderUserId) || "";
//       //			if (name == "") {
//       //				var parame = {
//       //					values : {
//       //						userId : senderUserId
//       //					}
//       //				}
//       //				doAjax(GETINFO, "POST", parame, function(data) {
//       //					name = data.data.nickname;
//       //					var isRemind = $api.getStorage("isRemind") || "";
//       //					if (isRemind == "") {
//       //						api.notification({
//       //							notify : {
//       //								content : convertMsg(objectName, contenttext),
//       //								title : name
//       //							}
//       //						}, function(ret, err) {
//       //						});
//       //					}
//       //						var  rongCloud2    =  api.require("rongCloud2")
//       //
//       //						rongCloud2.setConversationNotificationStatus({
//       //							conversationType : conversationType,
//       //							targetId : targetId,
//       //							notificationStatus : 'NOTIFY'
//       //						}, function(ret, err) {
//       //							if (ret.status == 'success') {
//       //									console.log("-----------------");
//       //							} else {
//       //								err.where = "rong.setConversationNotificationStatus 1";
//       //								//			        d.reject(err);
//       //							}
//       //						})
//       //				}, function() {
//       //				})
//       //			} else {
//       //
//       //				var isRemind = $api.getStorage("isRemind") || "";
//       //				if (isRemind == "") {
//       //					api.notification({
//       //						notify : {
//       //							content : convertMsg(objectName, contenttext),
//       //							title : name
//       //						}
//       //					}, function(ret, err) {
//       //					});
//       //
//       //						var  rongCloud2  =   api.require("rongCloud2");
//       //						rongCloud2.setConversationNotificationStatus({
//       //							conversationType : conversationType,
//       //							targetId : targetId,
//       //							notificationStatus : 'NOTIFY'
//       //						}, function(ret, err) {
//       //							if (ret.status == 'success') {
//       //								//d.resolve(ret);
//       //								console.log("-----------------");
//       //							} else {
//       //
//       //								//d.reject(err);
//       //							}
//       //						})
//       //				}
//       //			}
//     }
//
//   }
//   if (message.objectName == 'RC:ImgMsg') {
//     contenttext = message.content.imageUrl;
//     console.log(contenttext);
//
//   }
//
//   if (message.objectName == 'RC:VcMsg') {
//     contenttext = message.content.voicePath;
//     duration = message.content.duration;
//   }
//
//   if (message.objectName == 'RC:LBSMsg') {
//
//     poi = message.content.poi;
//     latitude = message.content.latitude;
//     longitude = message.content.longitude;
//     contenttext = message.content.imagePath;
//
//     //	alert(poi+"|"+latitude+"|"+longitude+"|"+contenttext);
//   }
//
//   console.log('extra  :  ' + extra);
//
//   var sql = 'INSERT INTO msg(duration,contentextra,          contenttext,   		conversationType,     		extra,      	messageDirection,		 messageid,		  objectname,	receivedtime,senderuserid,sendstatus,sendtime,targetid,userid,createtime,status,poi,longitude,latitude)';
//   sql = sql + 'VALUES (\'' + duration + '\',\'' + contentextra + '\',\'' + contenttext + '\' ,\'' + conversationType + '\' ,\'' + extra + '\',\'' + messageDirection + '\',\'' + messageId + '\' ,\'' + objectName + '\' ,\'' + receivedTime +
//     '\',\'' + senderUserId + '\',\'' + sentStatus + '\',\'' + sentTime + '\',\'' + targetId + '\',\'' + userId + '\',\'' + new Date().getTime() + '\',\'1\',\'' + poi + '\',\'' + longitude + '\',\'' + latitude + '\')';
//
//   upDataSql(sql, function () {
//     console.log('保存消息成功');
//     //initAppIconBadge();
//
//     api.execScript({
//       script: 'initMessage("' + conversationType + '");',
//       name: 'index1'
//     });
//
//     //		api.execScript({
//     //			script : 'initMessage("new");',
//     //			name : "chat_win",
//     //			frameName : "chat_frm"
//     //		});
//
//   });
// };
//
// //退出 融云
// function exitRong(fun) {
//   var rongCloud2 = api.require('rongCloud2');
//   // 之前调用 init 和 connect 的代码省略
//   rongCloud2.disconnect({
//     isReceivePush: false
//   }, function (ret, err) {
//     if ('success' == ret.status) {
//       api.toast({
//         msg: '断开连接成功!'
//       });
//       fun();
//     }
//   });
//   // 断开，且不再接收 Push
// }
//
/////////////////////////融云完毕//////////////////////////

/**
 *ibm  监听事件
 * @param {Object} name
 * @param {Object} funs
 */
function ibmAddEventListener(name, funs) {
    api.addEventListener({
        name: name
    }, function (ret, err) {
        funs(ret);
    });
}

function setLightKey(key) {

    var lightKey = '<span class=\'main1_blue\'>' + searchKey + '</span>';

    if (key && key.indexOf(searchKey) >= 0) {
        key = key.split(searchKey).join(lightKey);
    }

    return key;
}

function setPhone(phone) {

    return phone.substring(0, 3) + '-' + phone.substring(3, 7) + '-' + phone.substring(7, 11);

}

//验证函数
/**
 * if(!isCanPass(value,type)){
 *
 *	api.toast({
 *	  msg: '请输入正确的团队ID',
 *	 duration: 2000,
 *	  location: 'middle'
 *	});
 *
 * }
 *
 *
 */

function isCanPass(value, type) {
    var regBox = {
        regMobile: /^[0-9]*$/ //判断是否是数字
    };

    if (type == 1) {
        var rvalue = regBox.regMobile.test(value);
        if (!(rvalue && value)) {
            //验证不通过
            return false;
            return;
        } else {
            //验证通过
            return true;
        }
    }

}

// 拨打电话
function dadianhua(num) {

location.href = 'tel:'+ num;

}

///////////////////////////公共//////////////////////////

// 打开分享
function fnFen(shareData) {

    api.openFrame({
        name: 'z_share_frm',
        url: './z_share_frm.html',
        bounces: false,
        rect: {
            x: 0,
            y: 0,
            w: 'auto',
            h: 'auto'
        },
        pageParam: shareData,
        hScrollBarEnabled: false,
        vScrollBarEnabled: false
    });

}

//判断游客登录跳转登录页--底部导航
function isVisitorLogin(pCallBack) {

    if (!$api.getStorage('allUser')) {

        pCallBack(false);

        openWindow('login_win', '../../html/login_win.html');

        return;

    } else {
        //返回true说明登录
        pCallBack(true);

        return;
    }

}

//只在登陆下进行的操作
function isVisitorLogin2(pCallBack) {

    if (!$api.getStorage('allUser')) {

        pCallBack(false);

        return;

    } else {
        //返回true说明登录
        pCallBack(true);

        return;
    }

}

//分页
var skip = 1;
var limit = 10;

function initDataaa(where, addressId) {
    var parame = {
        values: {}
    };
    LoadingShow();
    doAjax(addressesgetlist, 'POST', parame, function (data) {
        LoadingClose();
        //成功执行函数
        if (data.statusCode == '200') {
            if (where == 1) {
                if (data.data.length > 0) {
                    temp1 = doT.template(document.getElementById('template_list1').innerHTML);
                    $api.html($api.byId('list1'), temp1(data.data[0]));
                    username = data.data[0].username;
                    cellphone = data.data[0].cellphone;
                    address = data.data[0].address;
                    addressId = data.data[0].id;
                }
                return;
            }
            if (data.data.length == 1) {
                var idd = data.data[0].id;
                fnDefaulttt(idd);
                return;
            }

        } else {
            api.toast({
                msg: data.message,
                duration: 2000,
                location: 'middle'
            });
        }
    }, function (errorData) {
        //失败执行函数
    });
}

function fnDefaulttt(idd) {
    var parame = {
        values: {
            id: idd
        }
    };
    LoadingShow();
    doAjax(setDefault, 'POST', parame, function (data) {
        LoadingClose();
        //成功执行函数
        if (data.statusCode == '200') {
            var jsfun = 'initData1();';
            api.execScript({
                name: 'firm_order_win',
                frameName: 'firm_order_frm',
                script: jsfun
            });
            setTimeout(function () {
                api.closeWin();
            }, 500);
        } else {
            api.toast({
                msg: data.message,
                duration: 2000,
                location: 'middle'
            });
        }
    }, function (errorData) {
        //失败执行函数
    });
}

// 转换时间格式
function fuGetTime(num, time) {
    if (num == 1) { //yyyy-MM-dd hh:mm:ss
        var time1 = time.replace('T', ' ').replace('.000Z', '');
        time1 = getTimestamp(time1) + 28800000;
        time1 = getDateTime2(time1);
        return time1;
    }
    if (num == 2) { //yyyy-MM-dd
        var time1 = time.replace('T', ' ').replace('.000Z', '');
        time1 = getTimestamp(time1) + 28800000;
        time1 = getDateTime2(time1);
        var time2 = time1.substring(0, 10);
        return time2;
    }
    if (num == 3) { //yyyy年MM月dd日 hh:mm:ss
        var time1 = time.replace('T', ' ').replace('.000Z', '');
        time1 = getTimestamp(time1) + 28800000;
        time1 = getDateTime2(time1, 1);
        return time1;
    }
    if (num == 4) { //hh:mm
        var time1 = time.replace('T', ' ').replace('.000Z', '');
        time1 = getTimestamp(time1) + 28800000;
        time1 = getDateTime2(time1);
        time2 = time1.substring(11, 16);
        return time2;
    }
    if (num == 5) { //ms
        var time1 = time.replace('T', ' ').replace('.000Z', '');
        time1 = getTimestamp(time1) + 28800000;
        return time1;
    }
    if (num == 6) { //MM-dd
        var time1 = time.replace('T', ' ').replace('.000Z', '');
        time1 = getTimestamp(time1) + 28800000;
        time2 = getDateTime2(time1, 3);
        return time2;
    }
    if (num == 7) { //yyyy年MM月dd日
        var time1 = time.replace('T', ' ').replace('.000Z', '');
        time1 = getTimestamp(time1) + 28800000;
        time1 = getDateTime2(time1, 1);
        time2 = time1.substring(0, 11);
        return time1;
    }
}

//时间戳转化成时间  yyyy-MM-dd  hh:ss
function getDateTime2(timeNumber, num) {
    var changeTime = new Date();
    var result;
    changeTime.setTime(timeNumber);

    var changeday = changeTime.getDate();
    var changemonth = changeTime.getMonth() + 1;
    var changeyear = changeTime.getFullYear();
    var changeHours = changeTime.getHours();

    var changeMinutes = changeTime.getMinutes();
    if (num != 2) {
        if (changemonth < 10) {
            changemonth = '0' + changemonth;
        }
        if (changeday < 10) {
            changeday = '0' + changeday;
        }
    }
    if (changeHours < 10) {
        changeHours = '0' + changeHours;
    }
    if (changeMinutes < 10) {
        changeMinutes = '0' + changeMinutes;
    }

    if (num == 1) {
        result = changeyear + '年' + changemonth + '月' + changeday + '日 ' + changeHours + ':' + changeMinutes;
    } else if (num == 2) {
        result = changeyear + '年' + changemonth + '月' + changeday + '日 ';
    } else if (num == 3) {
        result = changemonth + '/' + changeday;
    } else {
        result = changeyear + '-' + changemonth + '-' + changeday + ' ' + changeHours + ':' + changeMinutes;
    }
    return result;

}

/////////////////////////自定义confirm组件///////////
function ZConfirm(obj, callback) {
    if (obj.title == '') {
        console.log('需要title参数');
    }
    api.openFrame({
        name: 'z_confirm',
        url: '../../html/main5/z_confirm.html',
        bounces: false,
        rect: {
            x: 0,
            y: 0,
            w: 'auto',
            h: 'auto'
        },
        pageParam: {
            title: obj.title
        },
        hScrollBarEnabled: false,
        vScrollBarEnabled: false
    });
    api.addEventListener({
        name: 'zconfirm'
    }, function (ret, err) {
        callback(ret.value, err);
        api.removeEventListener({
            name: 'zconfirm'
        });
    });

}

//刷新数据
function refreshInitData() {
    page = 1;
    initData();
}

var doAjaxx = function (url, type, params, successFun, errorFun) {

    console.log(JSON.stringify($api.getStorage('allUser')));

    if ($api.getStorage('allUser')) {
        var value = $api.getStorage('allUser').userToken || '';
        var user_id = $api.getStorage('allUser').userId || '';
    } else {
        var value = '';
        var user_id = '';
    }

    if (params.values == null) {
        params.values = {};
    }

    var reqDate = Date.now();
    var appId = 'appid';
    var appkey = 'appkey';
    //var reqKey ='openkitadmin';
    var reqKey = MD5(appId + 'openkit' + appkey + 'openkit' + reqDate).toUpperCase();
    var Token = MD5(user_id + 'openkit' + value + 'openkit' + reqDate).toUpperCase();

    params.values.reqToken = Token;
    params.values.uid = user_id;
    params.values.reqDate = reqDate;
    params.values.reqKey = reqKey;

    console.warn('接口地址和入参！！' + url + '  ' + JSON.stringify(params) + '时间戳：' + reqDate + '加密key：' + reqKey);

    api.ajax({
        url: url,
        method: type,
        data: params,
        headers: {
            reqKey: reqKey,
            reqDate: reqDate,
            uid: user_id,
            reqToken: Token
        },
        timeout: 30
    }, function (ret, err) {

        if (ret) {
            console.warn('接口成功返回！！' + JSON.stringify(ret));

            if (ret.code == '4001') {

                api.alert({
                    title: '账号异常',
                    msg: '账号已在其他地方登录,请重新登录'
                }, function (ret, err) {

                    $api.rmStorage('allUser');
                    $api.rmStorage('userRongToken');
                    api.rebootApp();
                });
            }
            successFun(ret);
        } else {
            LoadingClose();
            api.refreshHeaderLoadDone();
            errorFun(err);
            console.warn('接口返回失败！！' + JSON.stringify(err));
            api.toast({
                msg: '网络连接超时',
                location: 'middle'
            });
        }

    });
};

// 保留小数点后一位
function toFixedone(num) {
    if (num % 1 === 0) {
        return num || '-';
    } else {
        return num.toFixed(1) || '-';
    }
}

// 比较大小
function toPanduan(num, min, max) {
    if ((num < min) || (num > max) || (num == min) || (num == max)) {
        return true;
    } else {
        return false;
    }
}

//默认获取前一天时间
function fnLastday() {
    var myDate = new Date();
    var myDate1 = myDate.getTime() - 86400000;
    var myDate2 = getDateTime2(myDate1, 2).substring(2) + ' 00:00 - ' + getDateTime2(myDate1, 2).substring(2) + ' 23:59';
    console.warn(myDate2);
    return myDate2;
}

// 切割时间、回显
function addTime(time, num) {
    var all_time1 = [];
    var all_time2 = [];
    // var time ="18年6月28日 00:00 - 18年6月28日 23:59";
    var reg1 = /\d{2}年/g;
    var reg2 = /\d{1,2}月/g;
    var reg3 = /\d{1,2}日/g;
    var reg4 = /\d{2}:\d{2}/g;
    var reg11 = time.match(reg1);
    var reg22 = time.match(reg2);
    var reg33 = time.match(reg3);
    var reg44 = time.match(reg4);
    var reg441 = reg44[0].split(':');
    var reg442 = reg44[1].split(':');
    if (num == 1) {
        all_time1.push(reg11[0]);
        all_time1.push(reg22[0]);
        all_time1.push(reg33[0]);
        all_time1.push(reg441[0] + '时');
        all_time1.push(reg441[1] + '分');
        return all_time1;
    } else if (num == 2) {
        all_time2.push(reg11[1]);
        all_time2.push(reg22[1]);
        all_time2.push(reg33[1]);
        all_time2.push(reg442[0] + '时');
        all_time2.push(reg442[1] + '分');
        return all_time2;
    }
    console.warn(JSON.stringify(all_time1 + '||' + all_time2));
    // console.warn(all_time1);
}

// 传参时间，开始和结束
function toChuantime(time, num) {
    // var time = "18年6月28日 00:00 - 18年6月28日 23:59";
    var reg2 = /\d{1,2}月/g;
    var reg3 = /\d{1,2}日/g;
    var reg22 = time.match(reg2);
    var reg33 = time.match(reg3);
    var monthStart = parseInt(reg22[0]);
    var dayStart = parseInt(reg33[0]);
    var monthOver = parseInt(reg22[1]);
    var dayOver = parseInt(reg33[1]);
    var monthStart1 = reg22[0];
    var dayStart1 = reg33[0];
    var monthOver1 = reg22[1];
    var dayOver1 = reg33[1];
    if (monthStart < 10) {
        monthStart1 = '0' + monthStart + '月';
    }
    if (dayStart < 10) {
        dayStart1 = '0' + dayStart + '日';
    }
    if (monthOver < 10) {
        monthOver1 = '0' + monthOver + '月';
    }
    if (dayOver < 10) {
        dayOver1 = '0' + dayOver + '日';
    }
    var timee = time.split(' - ');
    var timee1 = timee[0].replace(/\d{1,2}月\d{1,2}日/g, monthStart1 + dayStart1);
    var timee2 = timee[1].replace(/\d{1,2}月\d{1,2}日/g, monthOver1 + dayOver1);
    var timee3 = timee1 + '|' + timee2;
    console.warn(timee1 + '||' + timee1 + '||3592');
    var time1 = timee3.replace(/年/g, '-');
    var time2 = time1.replace(/月/g, '-');
    var time3 = time2.replace(/日/g, '');
    var timeAll = time3.split('|');
    console.warn(timeAll[0] + '||' + timeAll[1] + '||3597');
    if (num == 1) {
        return '20' + timeAll[0];
    } else if (num == 2) {
        return '20' + timeAll[1];
    }
}

// 切割时间为['*年','*月','*日']

function threeTime(num, time) {
    if (num == 1) {
        var timeArr = [];
        var time = getDateTime(Date.parse(new Date()), 1);
        var time3 = time.split('-');
        timeArr.push(time3[0].substring(2, 4) + '年');
        timeArr.push(time3[1] + '月');
        timeArr.push(time3[2] + '日');
        return timeArr;
    } else if (num == 2) {
        var timeArr;
        var time = getDateTime(Date.parse(new Date()), 1);
        var time3 = time.split('-');
        timeArr = time3[0].substring(2, 4) + '年' + time3[1] + '月' + time3[2] + '日';
        return timeArr;
    } else if (num == 3) {
        var timeArr = [];
        var time1 = time.split('年');
        var time2 = time1[1].split('月');
        timeArr.push(time1[0] + '年');
        timeArr.push(time2[0] + '月');
        timeArr.push(time2[1]);
        return timeArr;
    }

}

//截取日期前10位  2018-08-09 18:48--2018-08-09
function tenTime(date) {
    if (date != '' && date != null) {
        var time = date.substring(0, 10);
    }
    return time;
}

//我的活动 时间处理
function control_time(time1, time2) {

    if (time1.substring(6, 10) == time2.substring(6, 10)) {
        var time11;
        time11 = time1.slice(6, time1.length - 3);
        var time22;
        time22 = time2.substr(-8, 5);
        // console.log(time11,time22);
        return time11 + '至' + time22;
    } else {
        var time11;
        time11 = time1.slice(6, time1.length - 3);
        var time22;
        time22 = time2.slice(6, time1.length - 3);
        // console.log(time11,time22);
        return time11 + '至' + time22;
    }
}

// 对标签转义
function escapeHTMLString(str) {
    if (str != '' && str != null) {
        str = str.replace(/</g, '&lt;');
        str = str.replace(/>/g, '&gt;');
    }
    return str;
}

/////////////////////////////////////南丁项目//////////////////////
function checkIdcard(num) {
    num = num.toUpperCase();
    //身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X。
    if (!(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num))) {
        //alert('输入的身份证号长度不对，或者号码不符合规定！\n15位号码应全为数字，18位号码末位可以为数字或X。');
        return false;
    }
    //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
    //下面分别分析出生日期和校验位
    var len, re;
    len = num.length;
    if (len == 15) {
        re = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/);
        var arrSplit = num.match(re);

        //检查生日日期是否正确
        var dtmBirth = new Date('19' + arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4]);
        var bGoodDay;
        bGoodDay = (dtmBirth.getYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]));
        if (!bGoodDay) {
            //alert('输入的身份证号里出生日期不对！');
            return false;
        } else {
            //将15位身份证转成18位
            //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
            var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
            var nTemp = 0, i;
            num = num.substr(0, 6) + '19' + num.substr(6, num.length - 6);
            for (i = 0; i < 17; i++) {
                nTemp += num.substr(i, 1) * arrInt[i];
            }
            num += arrCh[nTemp % 11];
            return true;
        }
    }
    if (len == 18) {
        re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/);
        var arrSplit = num.match(re);

        //检查生日日期是否正确
        var dtmBirth = new Date(arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4]);
        var bGoodDay;
        bGoodDay = (dtmBirth.getFullYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]));
        if (!bGoodDay) {
            //alert('输入的身份证号里出生日期不对！');
            return false;
        } else {
            //检验18位身份证的校验码是否正确。
            //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
            var valnum;
            var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
            var nTemp = 0, i;
            for (i = 0; i < 17; i++) {
                nTemp += num.substr(i, 1) * arrInt[i];
            }
            valnum = arrCh[nTemp % 11];
            if (valnum != num.substr(17, 1)) {
                //alert('18位身份证的校验码不正确！应该为：' + valnum);
                return false;
            }
            return true;
        }
    }
    return false;
}

//时间判断逻辑
// 活动、问答、资讯 列表页
// 今天：显示时分  例（12:12）
// 昨天：显示月日 例（07-06 ）
// 去年：显示年月日 例（2017-07-07）
// 活动、问答、资讯、评论详情页-
// 今天：显示时分  例（12:12）
// 昨天：显示月日 +时分 例（07-06 12:12）
// 去年：显示年月日+时分 例（2017-07-07 12:12
// type=1 列表页
// type=2 详情页
function timePan(type, time) {
    if (time == null || time == '') {
        return '';
    }
    // date1=new Date();
    // timeStamp1 = Date.parse(new Date());
    date = time.substring(0, 19);
    date = date.replace(/-/g, '/');
    timeStamp = Date.parse(new Date(date)); //时间转时间搓
    nowtimeStamp = Date.parse(new Date());
    var newTime1 = new Date(nowtimeStamp);
    var newYear1 = newTime1.getFullYear(); //年
    var newMonth1 = newTime1.getMonth() + 1; //月
    var newDay1 = newTime1.getDate(); //日
    var newTime = new Date(timeStamp);
    var newYear = newTime.getFullYear(); //年
    var newMonth = newTime.getMonth() + 1; //月
    var newDay = newTime.getDate(); //日
    var newHours = newTime.getHours(); //时
    var newMinutes = newTime.getMinutes(); //分
    var newSeconds = newTime.getSeconds(); //秒

    if (newMonth < 10) {
        newMonth = '0' + newMonth;
    }
    if (newDay < 10) {
        newDay = '0' + newDay;
    }

    if (newHours < 10) {
        newHours = '0' + newHours;
    }
    if (newMinutes < 10) {
        newMinutes = '0' + newMinutes;
    }
    if (newSeconds < 10) {
        newSeconds = '0' + newSeconds;
    }
    if (type == 1) {
        if (newYear == newYear1) {
            if (newYear == newYear1 && newMonth == newMonth1 && newDay == newDay1) {
                return newHours + ':' + newMinutes;
            }
            return newMonth + '-' + newDay;
        }
        return newYear + '-' + newMonth + '-' + newDay;
    }
    if (type == 2) {
        if (newYear == newYear1 && newMonth == newMonth1 && newDay == newDay1) {
            return newHours + ':' + newMinutes;
        }
        if (newYear == newYear1) {
            return newMonth + '-' + newDay + ' ' + newHours + ':' + newMinutes;
        }
        return newYear + '-' + newMonth + '-' + newDay + ' ' + newHours + ':' + newMinutes;
    }

}

// 活动时间显示
// 今年不跨天 7月23日 12:12 至 23:30
// 今年跨天 7月23日 12:12 至  7月24日 23:30
// 去年不跨天2017年7月23日 12:12 至 23:30
// 去年跨天 2017年7月23日 12:12 至  2017年7月24日 23:30

function changetimeND(hisTime, hisTime1) {

    if (hisTime == null) {
        hisTime = '1900-01-01 00:00:00.0';
    }
    date = hisTime.substring(0, 19);
    date = date.replace(/-/g, '/');
    timeStamp = Date.parse(new Date(date)); //时间转时间搓
    var newTime = new Date(timeStamp);
    var newYear = newTime.getFullYear(); //年
    var newMonth = newTime.getMonth() + 1; //月
    var newDay = newTime.getDate(); //日
    var newHours = newTime.getHours(); //时
    var newMinutes = newTime.getMinutes(); //分
    var newSeconds = newTime.getSeconds(); //秒

    if (newMonth < 10) {
        newMonth = '0' + newMonth;
    }
    if (newDay < 10) {
        newDay = '0' + newDay;
    }

    if (newHours < 10) {
        newHours = '0' + newHours;
    }
    if (newMinutes < 10) {
        newMinutes = '0' + newMinutes;
    }
    if (newSeconds < 10) {
        newSeconds = '0' + newSeconds;
    }

    //第二个时间
    if (hisTime1 == null) {
        hisTime1 = '1900-01-01 00:00:00.0';
    }
    date1 = hisTime1.substring(0, 19);
    date1 = date1.replace(/-/g, '/');
    timeStamp1 = Date.parse(new Date(date1)); //时间转时间搓
    var newTime1 = new Date(timeStamp1);
    var newYear1 = newTime1.getFullYear(); //年
    var newMonth1 = newTime1.getMonth() + 1; //月
    var newDay1 = newTime1.getDate(); //日
    var newHours1 = newTime1.getHours(); //时
    var newMinutes1 = newTime1.getMinutes(); //分
    var newSeconds1 = newTime1.getSeconds(); //秒

    if (newMonth1 < 10) {
        newMonth1 = '0' + newMonth1;
    }
    if (newDay1 < 10) {
        newDay1 = '0' + newDay1;
    }

    if (newHours1 < 10) {
        newHours1 = '0' + newHours1;
    }
    if (newMinutes1 < 10) {
        newMinutes1 = '0' + newMinutes1;
    }
    if (newSeconds1 < 10) {
        newSeconds1 = '0' + newSeconds1;
    }

    var myDateNowwww = new Date(); //
    var nonwwwww = myDateNowwww.getFullYear(); //

    if (newYear == nonwwwww) {

        //今年然后判断是不是超过一天
        if (newDay != newDay1) {
            var timee = newMonth + '-' + newDay + ' ' + newHours + ':' + newMinutes;
            var timee1 = newMonth1 + '-' + newDay1 + ' ' + newHours1 + ':' + newMinutes1;

            return timee + ' 至 ' + timee1;
        } else {
            return newMonth + '-' + newDay + ' ' + newHours + ':' + newMinutes + ' 至 ' + newHours1 + ':' + newMinutes1;
        }

    } else {

        if (newDay != newDay1) {
            var timee = newYear + '-' + newMonth + '-' + newDay + ' ' + newHours + ':' + newMinutes;
            var timee1 = newYear1 + '-' + newMonth1 + '-' + newDay1 + ' ' + newHours1 + ':' + newMinutes1;

            return timee + ' 至 ' + timee1;
        } else {
            return newYear + '-' + newMonth + '-' + newDay + ' ' + newHours + ':' + newMinutes + ' 至 ' + newHours1 + ':' + newMinutes1;
        }

    }

    return timee;
}

//限制字数
function getChangeName(key) {

    if (key.length > 7 && key != '') {
        return key.substring(0, 7) + '..';
    } else {
        return key;
    }

}

// 1未认证  2认证中 3认证成功 4认证失败
function changeUserAttestation(index) {

    var a = [
        '',
        '未认证',
        '认证中',
        '认证成功',
        '认证失败'];
    return a[index];

}

///手机号//
function fnIDcare(numberrrrr) {
    if (numberrrrr.length > 16) {
        var numberrrrr2 = numberrrrr.substring(0, 11) + '***' + numberrrrr.substring(14, 18);
    } else {
        var numberrrrr2 = numberrrrr.substring(0, 11) + '***' + numberrrrr.substring(14, 15);
    }

    return numberrrrr2;
}

function splitStr(imgs) {
    if (imgs.indexOf(',') != -1) {
        return imgs.split(',');
    } else {
        if (imgs) {
            return [imgs];
        } else {
            return [];
        }
    }
}

//转换时间！！！！
function changeTimeeeeToNumber(hisTimeeee) {

    var date = hisTimeeee.substring(0, 19);
    date = date.replace(/-/g, '/');
    changgggtime = Date.parse(new Date(date)); //时间转时间搓

    return changgggtime;
}

function formatDuring(mss) {
    var days = parseInt(mss / (1000 * 60 * 60 * 24));
    var hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = (mss % (1000 * 60)) / 1000;

    if (hours < 10 && hours > 0) {
        hours = '0' + hours;
    }
    if (minutes < 10 && minutes > 0) {
        minutes = '0' + minutes;
    }
    if (seconds < 10 && seconds > 0) {

        seconds = '0' + seconds;
    }

    if (Number(days) > 0) {
        return (days * 24 + Number(hours)) + '小时' + minutes + '分' + seconds;
        return;
    } else {
        return Number(hours) + '小时' + minutes + '分' + seconds;
    }

}

function formatDuring2(mss) {

    var t = new Date;
    var h = t.getHours();
    var m = t.getMinutes();
    var s = t.getSeconds();
    if (h < 10) {
        h = '0' + h;
    }
    if (m < 10) {
        m = '0' + m;
    }
    if (s < 10) {
        s = '0' + s;
    }
    h = h.length == 1 ? '0' + h : h;
    m = m.length == 1 ? '0' + m : m;
    s = s.length == 1 ? '0' + s : s;

    return time = h + ':' + m + ':' + s;

}

function Rad(d) {
    return d * Math.PI / 180.0;
    //经纬度转换成三角函数中度分表形式。
}

//计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
function GetDistance(lat1, lng1, lat2, lng2) {

    var radLat1 = Rad(lat1);
    var radLat2 = Rad(lat2);
    var a = radLat1 - radLat2;
    var b = Rad(lng1) - Rad(lng2);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137;
    // EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000;
    //输出为公里
    var temp = s;
    console.warn(s * 1000);

    return s * 1000;

}

//////////////////////tttttttttttttttttttttttttttttttttt开页面/////////////////

var voice_var_i = 'off';//播放状态
var voice_smdId = '';//播放第一个的smdid
function voiceplaying(el) {
    event.stopPropagation();
    if (voice_var_i == 'off') {
        var smdVoice = $api.attr(el, 'smdVoice') || '';

        api.download({
            url: getOssUrl(smdVoice),
            savePath: '',
            report: true,
            cache: true,
            allowResume: true
        }, function (ret, err) {
            if (ret.state == 1) {
                //下载成功
                voice_var_i = 'on';
                var smdId = $api.attr(el, 'smdId') || '';
                voice_smdId = smdId;
                $api.removeCls($api.byId('voice_' + smdId), 'left_horn');
                $api.addCls($api.byId('voice_' + smdId), 'left_horn1');

                api.startPlay({
                    path: ret.savePath
                }, function (ret, err) {
                    if (ret) {
                        var smdId = $api.attr(el, 'smdId') || '';
                        voice_smdId = smdId;
                        $api.addCls($api.byId('voice_' + smdId), 'left_horn');
                        $api.removeCls($api.byId('voice_' + smdId), 'left_horn1');
                        voice_var_i = 'off';
                        console.log(JSON.stringify(ret));
                    } else {
                        console.log(JSON.stringify(err));
                    }
                });

            } else {

            }
        });
    } else {
        api.stopPlay();
        $api.addCls($api.byId('voice_' + voice_smdId), 'left_horn');
        $api.removeCls($api.byId('voice_' + voice_smdId), 'left_horn1');
        voice_var_i = 'off';
        var smdId = $api.attr(el, 'smdId') || '';
        if (voice_smdId != smdId) {
            voiceplaying(el);
        }
    }

}

//获取#与#之间的内容
//var text = '#亲###3#爱的####customer#，您已成功购买了#brand#的商品，订单编号为#order#，请凭订单编号或⼿机号⾄商家处消费！#url# 请保留此短信，及时查看消费情况哦！'
//var regex=/\#(.+?)\#/g;
//var result;
//
//while((result=regex.exec(text))!=null) {
//console.log(result[1]);
//break;
//}

//比如：  alert(get3and3Message(allMessage));
function get3and3Message(text) {

    if (get3and3Message2(text) == '') {

        return '';
    } else {

        var regex = /\#(.+?)\#/g;
        var result;

        //全局匹配的时候 console.log(text.match(regex));
        //返回第一个匹配的：console.log(regex.exec(text));

        var jingAll = text.match(regex);

        console.log(jingAll.length);

        for (var i = 0; i < jingAll.length; i++) {

            var one = jingAll[i];
            if (one.indexOf(' ') >= 0 || one.indexOf('/n') >= 0 || one.indexOf('/r') >= 0 || one.indexOf('<br>') >= 0) {

            } else {

                while ((result = regex.exec(one)) != null) {
                    console.log(result[1]);

                    return result[1];
                    break;
                }

            }

        }

    }
//var regex = /\#(.+?)\#/g;
//var result;
//
//while ((result = regex.exec(text)) != null) {
//  console.log(result[1]);
//
//  return result[1];
//  break;
//}
//
//return '';

}

function javaTrim(str) {
    for (var i = 0; (str.charAt(i) == ' ') && i < str.length; i++) ;
    if (i == str.length) return ''; //whole string is space
    var newstr = str.substr(i);
    for (var i = newstr.length - 1; newstr.charAt(i) == ' ' && i >= 0; i--) ;
    newstr = newstr.substr(0, i + 1);
    return newstr;
}

//变色色色色色色色
function changeSmdContent(text) {

    var regex = /\#(.+?)\#/g;
    var result;

    //全局匹配的时候 console.log(text.match(regex));
    //返回第一个匹配的：console.log(regex.exec(text));

    var jingAll = text.match(regex);

    if (jingAll == null) {

        return text;
    } else {

        for (var i = 0; i < jingAll.length; i++) {

            var one = jingAll[i];
            if (one.indexOf(' ') >= 0 || one.indexOf('/n') >= 0 || one.indexOf('/r') >= 0 || one.indexOf('<br>') >= 0) {

                return text;
            } else {

                while ((result = regex.exec(one)) != null) {

                    var changeOneee = '<span class="colorrr1" onclick="dianJi(this)" name=' + result[0] + '>' + result[0] + '</span>';

                    text = text.replace(result[0], changeOneee) || '';

                    return text;
                    break;
                }

            }

        }

    }

//var text='# 1#2#3#4#5#6#7#8#9#10#11#12#13####'
//
//
//if(text.indexOf(' ')>=0 || text.indexOf('/n')>=0 || text.indexOf('/r')>=0 || text.indexOf('</br>')>=0){
//
////如果有
//console.log(1111)
//
//}else{
//
////
//console.log(2222)
//}

    return;

}

function changeSmdContent2(text2) {

    var regex2 = /\@(.+?)\:/g;
    var result;

    //全局匹配的时候 console.log(text.match(regex));
    //返回第一个匹配的：console.log(regex.exec(text));

    var jingAll2 = text2.match(regex2);

    if (jingAll2 != null) {

        var a = '';
        for (var i = 0; i < jingAll2.length; i++) {

            if (a.indexOf(jingAll2[i]) == -1) {
                a += jingAll2[i] + '';
                var changeOneee2 = '<span class="colorrr2" onclick="dianJi2(this)" name=' + jingAll2[i] + '>' + jingAll2[i] + '</span>';
                text2 = text2.replaceAll(jingAll2[i], changeOneee2);
            }

            //第一次：text2 =text2.replace(jingAll2[i],changeOneee2)||'';

            //第二次
//    var changeOneee2 = '<span class="colorrr2" onclick="dianJi2(this)" name=' + jingAll2[i] + '>' + jingAll2[i] + '</span>';
//    text2 = changeDiv(text2).replace(new RegExp(jingAll2[i], 'gi'), changeOneee2);

        }
        return text2;

    } else {

        return text2;
    }

}

function changeSmdContent33(content) {

    var list = dataImg;

    for (var j = 0; j < list.length; j++) {

        var imgsrc = '../../image/emotion/' + list[j].name + '.png';

        content = content.replaceAll(list[j].text, '<img width=\'20x\' height=\'20px\' style=\'display: inline-block\' src=\'' + imgsrc + '\'>');

    }

    return content;
}

String.prototype.replaceAll = function (s1, s2) {
    return this.replace(new RegExp(s1, 'gm'), s2);
};

function get3and3Message2(text) {

    var regex = /\#(.+?)\#/g;
    var result;

    while ((result = regex.exec(text)) != null) {
        console.log(result[1]);

        return result[1];
        break;
    }

    return '';

}

function get3and3Message3(text) {

    var regex = /\@(.+?)\:/g;
    var result;

    while ((result = regex.exec(text)) != null) {
        console.log(result[1]);

        return result[1];
        break;
    }

    return '';

}

function dianJi(el) {
    event.stopPropagation();
    var name = get3and3Message2($api.attr(el, 'name')) || '';

    var parame = {
        topicTitle: name
    };
    openWindow('topic_list_win', '../../html/main2/topic_list_win.html', parame);

}

function dianJi2(el) {
    event.stopPropagation();
    var name = get3and3Message3($api.attr(el, 'name')) || '';
    showNameee(name);
}

function dianJi3(el) {
    event.stopPropagation();
    var name = $api.attr(el, 'name') || '';
    showNameee(name);
}

function showNameee(getUserNickName) {

    var parame = {
        values: {
            userNickName: getUserNickName
        }
    };

    doAjax(findUserIdByUserNickName, 'POST', parame, function (successData) {

        //成功执行函数
        if (successData.code == 200) {

            var a = successData.data || '';
            if (a == '') {
                api.toast({
                    msg: '找不到该用户',
                    duration: 2000,
                    location: 'middle'
                });
                return;
            }

            var userId = successData.data.userId || '';
            if (userId == $api.getStorage('allUser').userId) {
                //自己的详情
                var parame = {
                    userId: userId,
                    laiyuan: ''
                };
                openWindowReload('person_win' + userId, '../../html/main5/person_win.html', parame);
            } else {
                //别人的详情
                var parame = {
                    userId: userId,
                    laiyuan: ''
                };
                //  alert(userId);
                openWindowReload('person_win1' + userId, '../../html/main2/person_win.html', parame);
            }

        } else {
            //非200错误返回的提示
            api.toast({
                msg: '找不到该用户',
                duration: 2000,
                location: 'middle'
            });
            return;

        }
    }, function (errorData) {
        //失败执行函数
    });

}

var changeTimeeee = function (hisTime, nowTime) {
    var now = nowTime ? nowTime : new Date().getTime(), diffValue = now - hisTime, result = '', minute = 1000 * 60,
        hour = minute * 60, day = hour * 24, halfamonth = day * 15, month = day * 30, year = month * 12,
        _year = diffValue / year,
        _month = diffValue / month, _week = diffValue / (7 * day), _day = diffValue / day, _hour = diffValue / hour,
        _min = diffValue / minute;

    var changeTime = new Date();
    changeTime.setTime(hisTime);

    //console.log(changeTime+"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    //console.log(convertDate(changeTime))
    var changeday = changeTime.getDate();
    var changemonth = changeTime.getMonth() + 1;
    var changeyear = changeTime.getFullYear();
    var changeHours = changeTime.getHours();
    //console.log("11" + hisTime + " "   + changeHours)
    var changeMinutes = changeTime.getMinutes();

    if (changeHours < 10) {
        changeHours = '0' + changeHours;
    }
    if (changeMinutes < 10) {
        changeMinutes = '0' + changeMinutes;
    }

    //console.log(_day+"***************************");

    //	if (_year >= 1)
    //		result = parseInt(_year) + "年前";
    //	else if (_month >= 1)
    //		result = parseInt(_month) + "个月前";
    //	else if (_week >= 1)
    //		result = parseInt(_week) + "周前";
    //	 alert(changeHours)
    if (_year >= 1) result = changeyear + '年' + changemonth + '月' + changeday + '日'; else if (_day >= 1) result = changemonth + '月' + changeday + '日'; else if (_hour >= 1) result = parseInt(_hour) + '个小时前'; else if (_min >=
        1) result = parseInt(_min) + '分钟前'; else result = '刚刚';
    return result;

};

function changeDiv(allDiv) {

    var dd = allDiv.replace(/<\/?.+?>/g, '');
    var dds = dd.replace(/ /g, '');//dds为得到后的内容

    console.log('改变数据||' + dds);
    return dds;

}

function changeDiv2(allDiv) {

    var reg = /<\/?span[^>]*>/gi;
    var aaa = allDiv.replace(reg, '');

    var reg2 = /<\/?p[^>]*>/gi;
    var aaa2 = aaa.replace(reg2, '');

    var reg3 = /<\/?img[^>]*>/gi;
    var aaa3 = aaa2.replace(reg3, '');

    var reg4 = /<\/?a[^>]*>/gi;
    var aaa4 = aaa3.replace(reg4, '');

    var reg5 = /<\/?div[^>]*>/gi;
    var aaa5 = aaa4.replace(reg5, '');

    var reg6 = /<\/?h1[^>]*>/gi;
    var aaa6 = aaa5.replace(reg6, '');

    return aaa6;

}

function removeTags(tagName, tagClass) {
    var tagElements = document.getElementById('editor');
    for (var m = 0; m < tagElements.length; m++) {
        if (tagElements[m].className == tagClass) {
            tagElements[m].parentNode.removeChild(tagElements[m]);
        }
    }
}

var openWindowReload = function (name, url, pageParam) {
    api.openWin({
        name: name,
        url: url,
        pageParam: pageParam,
        delay: 200,
        reload: true,
        slidBackEnabled: false,
        hScrollBarEnabled: false
    });
};

//改变状态
function changeReprintedStatus(type) {

    if (type == '1') {

        return '允许转载';
    } else {

        return '禁止转载';
    }

}

function changeRecordType(type) {

    if (type == '1') {
        return '发布了问题';
    } else if (type == '2') {
        return '关注了问题';
    } else if (type == '3') {
        return '回答了问题';
    } else if (type == '4') {
        return '对该回答打分';
    }

}

function changeUserNickName(type, name) {

    if (type == '0') {
        return name;
    } else {
        return '匿名用户';
    }

}

///////////////////////////////////////////////////////所有公共跳转的页面/////////////////////////////////
//打开自己的个人详情  type 给他人发信息时，判断信息来源于留学圈还是质问库
function openMyOneeee(el, type) {
    event.stopPropagation();
    var userId = $api.attr(el, 'userId') || '';
    if (userId == $api.getStorage('allUser').userId) {
        //自己的详情
        var parame = {
            userId: userId,
            laiyuan: type
        };
        openWindowReload('person_win', '../../html/main5/person_win.html', parame);
    } else {
        //别人的详情
        var parame = {
            userId: userId,
            laiyuan: type
        };
        //  alert(userId);
        openWindowReload('person_win1', '../../html/main2/person_win.html', parame);
    }

}

//动态详情
function openDongTaiMessage(el) {
    event.stopPropagation();
    var userId = $api.attr(el, 'userId') || '';
    var smdId = $api.attr(el, 'smdId') || '';
    var winNameee = $api.attr(el, 'winNameee') || '';
    var frmNameee = $api.attr(el, 'frmNameee') || '';

//别人的详情
    var parame = {
        smdId: smdId,
        winNameee: winNameee,
        frmNameee: frmNameee,
        userId: userId
    };

    openWindow('dongtai_xq_win', '../../html/main2/dongtai_xq_win.html', parame);

}

//动态详情
function openDongTaiMessage1(el) {
    event.stopPropagation();
    var userId = $api.attr(el, 'userId') || '';
    var smdId = $api.attr(el, 'smdId') || '';
    var winNameee = $api.attr(el, 'winNameee') || '';
    var frmNameee = $api.attr(el, 'frmNameee') || '';

//别人的详情
    var parame = {
        smdId: smdId,
        winNameee: winNameee,
        frmNameee: frmNameee,
        userId: userId
    };

    openWindow('dongtai_xq_win1', '../../html/main2/dongtai_xq_win.html', parame);

}

//问题详情
function openOneZhiWenKu(el) {
    event.stopPropagation();

    var malId = $api.attr(el, 'malId') || '';
    var winNameee = $api.attr(el, 'winNameee') || '';
    var frmNameee = $api.attr(el, 'frmNameee') || '';
    var type = $api.attr(el, 'type') || '';
    var parame = {
        malId: malId,
        winNameee: winNameee,
        frmNameee: frmNameee,
        type: type
    };
    openWindow('answer_xq_win', '../../html/main3/answer_xq_win.html', parame);

}

function openOneZhiWenKu1(el) {
    event.stopPropagation();

    var answerId = $api.attr(el, 'answerId') || '';
    var malId = $api.attr(el, 'malId') || '';
    var winNameee = $api.attr(el, 'winNameee') || '';
    var frmNameee = $api.attr(el, 'frmNameee') || '';
    var parame = {
        answerId: answerId,
        malId: malId,
        winNameee: winNameee,
        frmNameee: frmNameee
    };

    openWindow('answer_xq_win1', '../../html/main3/answer_xq_win1.html', parame);

}

//转发
function openZhuanFa(el) {

    var winNameee = $api.attr(el, 'winNameee') || '';
    var frmNameee = $api.attr(el, 'frmNameee') || '';
    var userNickName = $api.attr(el, 'userNickName') || '';
    var otherUserId = $api.attr(el, 'otherUserId') || '';
    var smdContent = $api.attr(el, 'smdContent') || '';
    var smdId = $api.attr(el, 'smdId') || '';
    var forwardCount = $api.attr(el, 'forwardCount') || '';
    var myDynamicVo = $api.attr(el, 'myDynamicVo') || '';
    var userImg = $api.attr(el, 'userImg') || '';

    if (myDynamicVo == 'null') {

        var parame = {
            winNameee: winNameee,
            frmNameee: frmNameee,
            userNickName: userNickName,
            otherUserId: otherUserId,
            smdContent: smdContent,
            smdId: smdId,
            forwardCount: forwardCount,
            myDynamicVo: '',
            userImg: userImg
        };
        openWindow('release_dynamic_win1', '../../html/main2/release_dynamic_win1.html', parame);
        return;
    } else {

        var aaa = eval('(' + myDynamicVo + ')');
        console.log('||' + JSON.stringify(aaa));

        var parame = {
            winNameee: winNameee,
            frmNameee: frmNameee,
            userNickName: userNickName,
            otherUserId: otherUserId,
            smdContent: smdContent,
            smdId: smdId,
            forwardCount: forwardCount,
            myDynamicVo: aaa,
            userImg: userImg

        };
        openWindow('release_dynamic_win1', '../../html/main2/release_dynamic_win1.html', parame);

    }

}

// 监听input框有没有值
function myFunction() {
    var x = document.getElementById('user_name').value;
    if (x) {
        $api.removeCls($api.dom('.closee'), 'hidden');
    } else {
        $api.addCls($api.dom('.closee'), 'hidden');
    }
}

// 点击叉号
function fnClear() {
    document.getElementById('user_name').value = '';
    $api.addCls($api.dom('.closee'), 'hidden');
}

function fixStatusBar(el) {
    var tEl = el;
    if (!el) {
        tEl = document.getElementById('header');
    }
    tEl.style.paddingTop = api.safeArea.top + 'px';
}

function fixStatusBariosX(el) {
    var tEl = el;
    if (!el) {
        tEl = document.getElementById('header');
    }
    tEl.style.paddingTop = api.safeArea.top * 2 + 'px';
}

// 监听input框有没有值
function myFunction() {
    var x = document.getElementById('user_name').value;
    if (x) {
        $api.removeCls($api.dom('.closee'), 'hidden');
    } else {
        $api.addCls($api.dom('.closee'), 'hidden');
    }
}

// 点击叉号
function fnClear() {
    document.getElementById('user_name').value = '';
    $api.addCls($api.dom('.closee'), 'hidden');
}

var pageNum = 1;
var pageSize = 20;

function Confirm(options, callback) {
    api.openFrame({
        name: 'z_confirm',
        url: 'widget://html/main1/z_confirm.html',
        pageParam: {
            options: options
        }
    });
    api.addEventListener({
        name: 'z_confirm'
    }, function (ret, err) {
        callback(ret, err);
        api.removeEventListener({
            name: 'z_confirm'
        });
    });
}

//时间戳转化成时间20180101
function getDateTime000(timeNumber, num) {
    var changeTime = new Date();
    changeTime.setTime(timeNumber);

    var changeday = changeTime.getDate();
    var changemonth = changeTime.getMonth() + 1;
    var changeyear = changeTime.getFullYear();
    var changeHours = changeTime.getHours();

    var changeMinutes = changeTime.getMinutes();
    if (num == 1) {

    } else {
        // if (changemonth < 10) {
        //   changemonth = '0' + changemonth;
        // }
        // if (changeday < 10) {
        //   changeday = '0' + changeday;
        // }
    }

    if ((changemonth == 6 && changeday > 21) || (changemonth == 7 && changeday < 23)) {
        xz = ' 巨蟹座';
    }
    if ((changemonth == 7 && changeday > 22) || (changemonth == 8 && changeday < 23)) {
        xz = ' 狮子座';
    }
    if ((changemonth == 8 && changeday > 22) || (changemonth == 9 && changeday < 23)) {
        xz = ' 处女座';
    }
    if ((changemonth == 9 && changeday > 22) || (changemonth == 10 && changeday < 24)) {
        xz = ' 天秤座';
    }
    if ((changemonth == 10 && changeday > 23) || (changemonth == 11 && changeday < 23)) {
        xz = ' 天蝎座';
    }
    if ((changemonth == 11 && changeday > 22) || (changemonth == 12 && changeday < 22)) {
        xz = ' 射手座';
    }
    if ((changemonth == 12 && changeday > 21) || (changemonth == 1 && changeday < 20)) {
        xz = ' 摩羯座';
    }
    if ((changemonth == 1 && changeday > 19) || (changemonth == 2 && changeday < 19)) {
        xz = ' 水瓶座';
    }
    if ((changemonth == 2 && changeday > 18) || (changemonth == 3 && changeday < 21)) {
        xz = ' 双鱼座';
    }
    if ((changemonth == 5 && changeday > 20) || (changemonth == 6 && changeday < 22)) {
        xz = ' 双子座';
    }
    if ((changemonth == 3 && changeday > 20) || (changemonth == 4 && changeday < 20)) {
        xz = ' 白羊座';
    }
    if ((changemonth == 4 && changeday > 19) || (changemonth == 5 && changeday < 21)) {
        xz = ' 金牛座';
    }
    //alert(changeyear+'|||'+changemonth+'|||'+changeday);
    var result = changeyear + '.' + changemonth + '.' + changeday + '' + xz;

    return result;

}

//截取12个字符
function jieshao(aaa) {
    var result = aaa;
    if (aaa.length > 12) {

        result = aaa.substring(0, 12) + '...';

    }

    return result;
}

//更新用户信息
function updateAlluser() {
    var parame = {
        values: {
            toUserId: $api.getStorage('allUser').userId
        }
    };
    doAjax(FINDUSERDETAIL, 'POST', parame, function (data) {
        if (data.code == '200') {
            var obj = {};
            for (var key in data.data.user) {
                obj[key] = data.data.user[key];
            }
            for (var key in data.data.userInfo) {
                obj[key] = data.data.userInfo[key];
            }
            $api.setStorage('allUser', obj);
        } else {
            api.toast({
                msg: data.msg,
                duration: 2000,
                location: 'middle'
            });
        }
    }, function (data) {

    });
}

//弹框
function showPop(type, callback, data) {
    api.openFrame({
        name: 'z_pop',
        url: 'widget://html/main1/z_pop.html',
        hScrollBarEnabled: false,
        vScrollBarEnabled: false,
        bounces: false,
        pageParam: {
            type: type,
            data: data
        }
    });
    api.addEventListener({
        name: 'z_pop'
    }, function (ret, err) {
        if (ret.value.index == 2) {
            console.log('测试');
            api.closeFrame({
                name: 'z_pop'
            });
            callback(ret.value);
        }
        api.removeEventListener({
            name: 'z_pop'
        });
    });
}

//更新课程表
function updateKCB(data, callback) {
    if (data) {
        $api.setStorage('kcb', data);
        return;
    }

    var params = {
        values: {}
    };
    doAjax(FINDSEMESTERBYUSERID, 'POST', params, function (data) {
        if (data.code == 200) {
            if (data.data.list.length == 0) {
                $api.setStorage('kcb', {});
                if (callback) {
                    callback();
                }
            } else {
                var params = {
                    values: {
                        semesterId: data.data.semesterId
                    }
                };
                doAjax(FINDTABLEBYUSERID, 'POST', params, function (data) {
                    if (data.code == 200) {
                        $api.setStorage('kcb', data.data);
                        if (callback) {
                            callback();
                        }
                    } else {
                        // api.toast({
                        //   msg: data.msg,
                        //   duration: 2000,
                        //   location: 'middle'
                        // });
                    }
                }, function (err) {
                    console.log(JSON.stringify(err));
                });
            }
        } else {
            api.toast({
                msg: data.msg,
                duration: 2000,
                location: 'middle'
            });
        }
    }, function (err) {
        console.log(JSON.stringify(err));
    });
}

//数字转汉子
function NumberToHanzi(number, bol) {
    var text = '';
    switch (Number(number)) {
        case 1:
            text = '一';
            break;
        case 2:
            text = '二';
            break;
        case 3:
            text = '三';
            break;
        case 4:
            text = '四';
            break;
        case 5:
            text = '五';
            break;
        case 6:
            text = '六';
            break;
        case 7:
            text = '七';
            if (bol) text = '天';
            break;
    }
    return text;
}

//判断是星期几
function numberToWeekDay(type) {
    var text = '';
    switch (Number(type)) {
        case 1:
            text = '星期一';
            break;
        case 2:
            text = '星期二';
            break;
        case 3:
            text = '星期三';
            break;
        case 4:
            text = '星期四';
            break;
        case 5:
            text = '星期五';
            break;
        case 6:
            text = '星期六';
            break;
        case 7:
            text = '星期天';
            break;
    }
    return text;
}

//字符串转数组--图片
function picArray(allImg) {

    if (allImg.substr(allImg.length - 1, 1) == ',') {
        allImg = allImg.substring(0, allImg.lastIndexOf(','));
    }
    allImg = allImg.split(',');
    return allImg;

}

// 播放视频 vidoeurl是已经拼接好的路径
function videoplaying(vidoeurl) {
    event.stopPropagation();
    var parame = {
        vidoeurl: vidoeurl
    };
    api.openWin({
        name: 'bofang_win',
        url: 'widget://html/bofang_win.html',
        pageParam: parame
    });
}

//动态列表
//点赞数加一，点赞图标变蓝
function adNumber(smdId) {

    $api.addCls($api.byId('id_' + smdId), 'zan1');
    $api.removeCls($api.byId('id_' + smdId), 'zan');
    $api.byId('idd_' + smdId).innerHTML = parseInt($api.byId('idd_' + smdId).innerHTML) + 1;

}

//点赞数减一
function subNumber(smdId) {

    $api.removeCls($api.byId('id_' + smdId), 'zan1');
    $api.addCls($api.byId('id_' + smdId), 'zan');
    $api.byId('idd_' + smdId).innerHTML = parseInt($api.byId('idd_' + smdId).innerHTML) - 1;

}

//点赞动态--zan未点赞,zan1已点赞
function fnZan1(el) {
    var smdId = $api.attr(el, 'smdId');
    console.warn('dianzna' + smdId);
    if ($api.hasCls($api.byId('id_' + smdId), 'zan1')) {
        //取消点赞

        var parame = {
            values: {
                smdId: smdId
            }
        };
//  LoadingShow();
        doAjax(CANNELMYDYNAMICPRAISE, 'POST', parame, function (data) {
//    LoadingClose();
            if (data.code == '200') {

                api.toast({
                    msg: '取消点赞',
                    duration: 2000,
                    location: 'middle'
                });
                $api.removeCls($api.byId('id_' + smdId), 'zan1');
                $api.addCls($api.byId('id_' + smdId), 'zan');
                $api.byId('idd_' + smdId).innerHTML = parseInt($api.byId('idd_' + smdId).innerHTML) - 1;

            } else {
                if (data.msg == '操作失败') {
                    api.toast({
                        msg: '您已取消点赞',
                        duration: 2000,
                        location: 'middle'
                    });
                    $api.removeCls($api.byId('id_' + smdId), 'zan1');
                    $api.addCls($api.byId('id_' + smdId), 'zan');
                    $api.byId('idd_' + smdId).innerHTML = parseInt($api.byId('idd_' + smdId).innerHTML) - 1;
                } else {
                    api.toast({
                        msg: data.msg,
                        duration: 2000,
                        location: 'middle'
                    });
                }
            }

        }, function (data) {

        });

    } else {
        //点赞
        var parame = {
            values: {
                smdId: smdId
            }
        };
//  LoadingShow();
        doAjax(SAVEMYDYNAMICPRAISE, 'POST', parame, function (data) {
//    LoadingClose();
            if (data.code == '200') {

                api.toast({
                    msg: '点赞成功',
                    duration: 2000,
                    location: 'middle'
                });
                $api.addCls($api.byId('id_' + smdId), 'zan1');
                $api.removeCls($api.byId('id_' + smdId), 'zan');
                $api.byId('idd_' + smdId).innerHTML = parseInt($api.byId('idd_' + smdId).innerHTML) + 1;

            } else {
                if (data.msg == '您已点赞') {
                    api.toast({
                        msg: '您已点赞',
                        duration: 2000,
                        location: 'middle'
                    });
                    $api.addCls($api.byId('id_' + smdId), 'zan1');
                    $api.removeCls($api.byId('id_' + smdId), 'zan');
                    $api.byId('idd_' + smdId).innerHTML = parseInt($api.byId('idd_' + smdId).innerHTML) + 1;
                } else {
                    api.toast({
                        msg: data.msg,
                        duration: 2000,
                        location: 'middle'
                    });
                }

            }

        }, function (data) {

        });

    }

}

//点赞动态评论--zan3未点赞,zan4已点赞
function fnZan(el) {
    var smdcId = $api.attr(el, 'smdcId');
    if ($api.hasCls($api.byId('id_' + smdcId), 'zan4')) {
        //取消点赞
        var parame = {
            values: {
                smdcId: smdcId
            }
        };
//  LoadingShow();
        doAjax(CANCELDYNAMICCOMMENTSPRAISE, 'POST', parame, function (data) {
//    LoadingClose();
            if (data.code == '200') {

                api.toast({
                    msg: '取消点赞',
                    duration: 2000,
                    location: 'middle'
                });
                $api.removeCls($api.byId('id_' + smdcId), 'zan4');
                $api.addCls($api.byId('id_' + smdcId), 'zan3');
                $api.byId('idd_' + smdcId).innerHTML = parseInt($api.byId('idd_' + smdcId).innerHTML) - 1;

            } else {
                if (data.msg == '操作失败') {
                    api.toast({
                        msg: '您已取消点赞',
                        duration: 2000,
                        location: 'middle'
                    });
                    $api.removeCls($api.byId('id_' + smdId), 'zan1');
                    $api.addCls($api.byId('id_' + smdId), 'zan');
                    $api.byId('idd_' + smdId).innerHTML = parseInt($api.byId('idd_' + smdId).innerHTML) - 1;
                } else {
                    api.toast({
                        msg: data.msg,
                        duration: 2000,
                        location: 'middle'
                    });
                }

            }

        }, function (data) {

        });

    } else {
        //点赞
        var parame = {
            values: {
                smdcId: smdcId
            }
        };
//  LoadingShow();
        doAjax(DYNAMICCOMMENTSPRAISE, 'POST', parame, function (data) {
//    LoadingClose();
            if (data.code == '200') {

                api.toast({
                    msg: '点赞成功',
                    duration: 2000,
                    location: 'middle'
                });
                $api.addCls($api.byId('id_' + smdcId), 'zan4');
                $api.removeCls($api.byId('id_' + smdcId), 'zan3');
                $api.byId('idd_' + smdcId).innerHTML = parseInt($api.byId('idd_' + smdcId).innerHTML) + 1;

            } else {
                if (data.msg == '您已点赞') {
                    api.toast({
                        msg: '您已点赞',
                        duration: 2000,
                        location: 'middle'
                    });
                    $api.addCls($api.byId('id_' + smdId), 'zan1');
                    $api.removeCls($api.byId('id_' + smdId), 'zan');
                    $api.byId('idd_' + smdId).innerHTML = parseInt($api.byId('idd_' + smdId).innerHTML) + 1;
                } else {
                    api.toast({
                        msg: data.msg,
                        duration: 2000,
                        location: 'middle'
                    });
                }

            }

        }, function (data) {

        });

    }

}

//删除动态评论
var delete_type = '';
var comment_length = '';//评论数
function fnDelete(el) {

    var smdcId = $api.attr(el, 'smdcId');
    var delete_type = $api.attr(el, 'delete_type');
    var comment_length = $api.attr(el, 'comment_length');

    var parame = {
        values: {
            smdcId: smdcId
        }
    };
    LoadingShow();
    doAjax(delDynamicComments, 'POST', parame, function (data) {
        LoadingClose();
        if (data.code == '200') {

            api.toast({
                msg: '删除成功',
                duration: 2000,
                location: 'middle'
            });

            if (delete_type == 1) {

                var jsfun = 'subAllComment("' + comment_all + '");';
                api.execScript({
                    name: 'dongtai_xq_win',
                    frameName: 'dongtai_xq_frm',
                    script: jsfun
                });

                var jsfun = 'subListAllComment("' + api.pageParam.smdId + '","' + comment_all + '");';
                api.execScript({
                    name: api.pageParam.winNameee,
                    frameName: api.pageParam.frmNameee,
                    script: jsfun
                });

                var jsfun = 'initData1();';
                api.execScript({
                    name: 'dongtai_xq_win',
                    frameName: 'dongtai_xq_frm',
                    script: jsfun
                });
                api.closeToWin({
                    name: 'dongtai_xq_win'
                });
            } else if (delete_type == 2) {

                //详情
                var jsfun = 'subComment();';
                api.execScript({
                    name: 'dongtai_xq_win',
                    frameName: 'dongtai_xq_frm',
                    script: jsfun
                });
                //列表
                var jsfun = 'subListCommnet("' + api.pageParam.smdId + '","' + comment_length + '");';
                api.execScript({
                    name: api.pageParam.winNameee,
                    frameName: api.pageParam.frmNameee,
                    script: jsfun
                });

                $api.byId('del_' + smdcId).remove();
                $api.byId('all_num').innerHTML = $api.byId('all_num').innerHTML - 1;
                if ($api.byId('all_num').innerHTML == 0) {
                    $api.removeCls($api.byId('seatAll'), 'hidden');
                }

            } else if (delete_type == 3) {

                var jsfun = 'subAllComment("' + comment_length + '");';
                api.execScript({
                    name: 'dongtai_xq_win',
                    frameName: 'dongtai_xq_frm',
                    script: jsfun
                });

                var jsfun = 'subListAllComment("' + api.pageParam.smdId + '","' + comment_length + '");';
                api.execScript({
                    name: api.pageParam.winNameee,
                    frameName: api.pageParam.frmNameee,
                    script: jsfun
                });

                $api.byId('del_' + smdcId).remove();
                $api.byId('allNumber').innerHTML = $api.byId('allNumber').innerHTML - 1;
                if ($api.byId('allNumber').innerHTML == 0) {
                    $api.removeCls($api.byId('seatAll'), 'hidden');
                }

            } else {

                var jsfun = 'subComment();';
                api.execScript({
                    name: 'dongtai_xq_win',
                    frameName: 'dongtai_xq_frm',
                    script: jsfun
                });

                //列表
                var jsfun = 'subListCommnet("' + api.pageParam.smdId + '");';
                api.execScript({
                    name: api.pageParam.winNameee,
                    frameName: api.pageParam.frmNameee,
                    script: jsfun
                });

                $api.byId('del_' + smdcId).remove();

            }

        } else {

            api.toast({
                msg: data.msg,
                duration: 2000,
                location: 'middle'
            });

        }

    }, function (data) {

    });

}

//增加动态列表评论数
function adListCommnet(smdId) {

    $api.byId('iddd_' + smdId).innerHTML = parseInt($api.byId('iddd_' + smdId).innerHTML) + 1;

}

//减少动态列表评论数
function subListCommnet(smdId) {

    $api.byId('iddd_' + smdId).innerHTML = parseInt($api.byId('iddd_' + smdId).innerHTML) - 1;

}

//删除主评论
function subListAllComment(smdId, comment_length) {
    var lsmdId = smdId;
    var lcomment_length = comment_length;
    $api.byId('iddd_' + lsmdId).innerHTML = parseInt($api.byId('iddd_' + lsmdId).innerHTML) - lcomment_length;

}

function getMsgCount(callback) {

    var params = {
        values: {}
    };
    doAjax(FINDMESSAGECOUNT, 'POST', params, function (data) {
        if (data.code == 200) {
            var allCount = 0;
            for (var key in data.data) {
                allCount += data.data[key];
            }
            callback(allCount, data.data);
        } else {
            api.toast({
                msg: data.msg,
                duration: 2000,
                location: 'middle'
            });
        }
    }, function (err) {
        console.log(JSON.stringify(err));
    });
}

//单机放大
function clickbig(el) {
    event.stopPropagation();
    var index = $api.attr(el, 'index');
    var imagess = $api.attr(el, 'images');
    var images = [];
    for (var i = 0; i < zhuangArrayImg(imagess).length; i++) {
        images[i] = getOssUrl(zhuangArrayImg(imagess)[i]);
    }

    var parame = {
        index: index,
        images: images,
        imagess: imagess
    };

    api.openWin({
        name: 'z_picc_win',
        url: '../main2/z_picc_win.html',
        pageParam: parame,
        delay: 200,
        slidBackEnabled: false,
        hScrollBarEnabled: false,
        animation: {
            type: 'fade',                //动画类型（详见动画类型常量）
            duration: 300
        }
    });
}

//'fs://download/'+ zhuangArrayImg(imagess)[ret.index] + '.jpg'
//单机放大
function clickbig1(el, index, imagess) {
    event.stopPropagation();
    var images = [];
    for (var i = 0; i < zhuangArrayImg(imagess).length; i++) {
        images[i] = getOssUrl(zhuangArrayImg(imagess)[i]);
    }
    var parame = {
        index: index,
        images: images,
        imagess: imagess
    };

    api.openWin({
        name: 'z_picc_win',
        url: '../main2/z_picc_win.html',
        pageParam: parame,
        delay: 200,
        slidBackEnabled: false,
        hScrollBarEnabled: false,
        animation: {
            type: 'fade',                //动画类型（详见动画类型常量）
            duration: 300
        }
    });
}

//刷新工具箱首页
function refreshUtilPage() {
    var jsfun = 'initData();';
    api.execScript({
        name: 'root1',
        frameName: 'main1_frm',
        script: jsfun
    });

}

//键盘收回
function inputBlur() {
    var input = $api.domAll('input');
    for (var i = 0; i < input.length; i++) {
        input[i].blur();
    }
    var textarea = $api.domAll('textarea');
    for (var i = 0; i < textarea.length; i++) {
        textarea[i].blur();
    }
    var div = $api.domAll('div[contenteditable]');
    for (var i = 0; i < div.length; i++) {
        div[i].blur();
    }
    document.activeElement.blur();
}

//删除智问库问题答案的评论
function deletee(el) {
    var commentsId = $api.attr(el, 'commentsId');
    var type = $api.attr(el, 'type');
    var isChoiceness = $api.attr(el, 'isChoiceness') || '';//全部回复，0.不是精选评论 1.是
    var parame = {
        values: {
            commentsId: commentsId
        }
    };
    LoadingShow();
    doAjax(DELCOMMENTSE, 'POST', parame, function (data) {
        LoadingClose();
        if (data.code == '200') {
            api.toast({
                msg: '删除成功',
                duration: 2000,
                location: 'middle'
            });
            var comments = 'delete_' + commentsId;
            $api.byId(comments).remove();
            if (type == -1) {
                initData();
                return;
            }
            if (type == 1) {
                $api.byId('all_num').innerHTML = $api.byId('all_num').innerHTML - 1;
            } else if (type == 2) {
                $api.byId('all_num1').innerHTML = $api.byId('all_num1').innerHTML - 1;
            } else if (type == 9) {
                if (isChoiceness == 0) {

                    var jsfun = 'initData();';
                    api.execScript({
                        name: 'comment_xq_win',
                        frameName: 'comment_xq_frm',
                        script: jsfun
                    });

                } else {

                    var jsfun = 'initData1();';
                    api.execScript({
                        name: 'comment_xq_win',
                        frameName: 'comment_xq_frm',
                        script: jsfun
                    });

                }
                api.closeWin();

            }

        } else {
            api.toast({
                msg: data.msg,
                duration: 2000,
                location: 'middle'
            });
        }
    }, function (data) {

    });
}

//删除智问库问题答案的评论
function deleteee(el) {
    var commentsId = $api.attr(el, 'commentsId');
    var type = $api.attr(el, 'type');
    var isChoiceness = $api.attr(el, 'isChoiceness') || '';//全部回复，0.不是精选评论 1.是
    var parame = {
        values: {
            commentsId: commentsId
        }
    };
    LoadingShow();
    doAjax(DELCOMMENTSS, 'POST', parame, function (data) {
        LoadingClose();
        if (data.code == '200') {
            api.toast({
                msg: '删除成功',
                duration: 2000,
                location: 'middle'
            });
            var comments = 'delete_' + commentsId;
            $api.byId(comments).remove();
            if (type == 1) {
                $api.byId('all_num').innerHTML = $api.byId('all_num').innerHTML - 1;
            } else if (type == 2) {
                $api.byId('all_num1').innerHTML = $api.byId('all_num1').innerHTML - 1;
            } else if (type == 9) {

                if (isChoiceness == 0) {

                    var jsfun = 'initData();';
                    api.execScript({
                        name: 'comment_xq_win1',
                        frameName: 'comment_xq_frm1',
                        script: jsfun
                    });

                } else {

                    var jsfun = 'initData1();';
                    api.execScript({
                        name: 'comment_xq_win1',
                        frameName: 'comment_xq_frm1',
                        script: jsfun
                    });

                }
                api.closeWin();

            }

        } else {
            api.toast({
                msg: data.msg,
                duration: 2000,
                location: 'middle'
            });
        }
    }, function (data) {

    });
}

//点赞智问库答案的评论--zan3未点赞,zan4已点赞
function fnZann(el) {
    var commentsId = $api.attr(el, 'commentsId');
    var type = $api.attr(el, 'type') || '';//3全部回复
    if ($api.hasCls($api.byId('id_' + commentsId), 'zan4')) {
        //取消点赞
        var parame = {
            values: {
                commentsId: commentsId
            }
        };
//  LoadingShow();
        doAjax(CANCELPRAISECOMMENTS, 'POST', parame, function (data) {
//    LoadingClose();
            if (data.code == '200') {

                api.toast({
                    msg: '取消点赞',
                    duration: 2000,
                    location: 'middle'
                });
                $api.removeCls($api.byId('id_' + commentsId), 'zan4');
                $api.addCls($api.byId('id_' + commentsId), 'zan3');
                $api.byId('idd_' + commentsId).innerHTML = parseInt($api.byId('idd_' + commentsId).innerHTML) - 1;
                if (type == 2) {

                    var jsfun = 'zsubNumber("' + commentsId + '");';
                    api.execScript({
                        name: 'answer_xq_win',
                        frameName: 'answer_xq_frm',
                        script: jsfun
                    });

                }
                if (type == 3) {
                    var jsfun = 'zsubNumber("' + commentsId + '");';
                    api.execScript({
                        name: 'comment_xq_win',
                        frameName: 'comment_xq_frm',
                        script: jsfun
                    });
                    var jsfun = 'zsubNumber("' + commentsId + '");';
                    api.execScript({
                        name: 'answer_xq_win',
                        frameName: 'answer_xq_frm',
                        script: jsfun
                    });
                }

            } else {

                api.toast({
                    msg: data.msg,
                    duration: 2000,
                    location: 'middle'
                });

            }

        }, function (data) {

        });

    } else {
        //点赞
        var parame = {
            values: {
                commentsId: commentsId
            }
        };
//  LoadingShow();
        doAjax(PRAISECOMMENTS, 'POST', parame, function (data) {
//    LoadingClose();
            if (data.code == '200') {

                api.toast({
                    msg: '点赞成功',
                    duration: 2000,
                    location: 'middle'
                });
                $api.addCls($api.byId('id_' + commentsId), 'zan4');
                $api.removeCls($api.byId('id_' + commentsId), 'zan3');
                $api.byId('idd_' + commentsId).innerHTML = parseInt($api.byId('idd_' + commentsId).innerHTML) + 1;
                if (type == 2) {

                    var jsfun = 'zadNumber("' + commentsId + '");';
                    api.execScript({
                        name: 'answer_xq_win',
                        frameName: 'answer_xq_frm',
                        script: jsfun
                    });

                }
                if (type == 3) {

                    var jsfun = 'zadNumber("' + commentsId + '");';
                    api.execScript({
                        name: 'comment_xq_win',
                        frameName: 'comment_xq_frm',
                        script: jsfun
                    });
                    var jsfun = 'zadNumber("' + commentsId + '");';
                    api.execScript({
                        name: 'answer_xq_win',
                        frameName: 'answer_xq_frm',
                        script: jsfun
                    });
                }

            } else {

                api.toast({
                    msg: data.msg,
                    duration: 2000,
                    location: 'middle'
                });

            }

        }, function (data) {

        });

    }

}

//分享
function shareToOtherApp(config) {
    api.openFrame({
        name: 'z_share',
        url: 'widget://html/main1/z_share.html',
        pageParam: config,
        bounces: false
    });
}

//点赞智问库问题的评论--zan3未点赞,zan4已点赞
function fnZannw(el) {
    var commentsId = $api.attr(el, 'commentsId');
    var type = $api.attr(el, 'type') || '';//3全部回复
    if ($api.hasCls($api.byId('id_' + commentsId), 'zan4')) {
        //取消点赞
        var parame = {
            values: {
                commentsId: commentsId
            }
        };
//  LoadingShow();
        doAjax(CANCELPRAISECOMMENTSS, 'POST', parame, function (data) {
//    LoadingClose();
            if (data.code == '200') {

                api.toast({
                    msg: '取消点赞',
                    duration: 2000,
                    location: 'middle'
                });
                $api.removeCls($api.byId('id_' + commentsId), 'zan4');
                $api.addCls($api.byId('id_' + commentsId), 'zan3');
                $api.byId('idd_' + commentsId).innerHTML = parseInt($api.byId('idd_' + commentsId).innerHTML) - 1;
                if (type == 3) {
                    var jsfun = 'zsubNumber("' + commentsId + '");';
                    api.execScript({
                        name: 'comment_xq_win1',
                        frameName: 'comment_xq_frm1',
                        script: jsfun
                    });
                }

            } else {

                api.toast({
                    msg: data.msg,
                    duration: 2000,
                    location: 'middle'
                });

            }

        }, function (data) {

        });

    } else {
        //点赞
        var parame = {
            values: {
                commentsId: commentsId
            }
        };
//  LoadingShow();
        doAjax(PRAISECOMMENTSS, 'POST', parame, function (data) {
//    LoadingClose();
            if (data.code == '200') {

                api.toast({
                    msg: '点赞成功',
                    duration: 2000,
                    location: 'middle'
                });
                $api.addCls($api.byId('id_' + commentsId), 'zan4');
                $api.removeCls($api.byId('id_' + commentsId), 'zan3');
                $api.byId('idd_' + commentsId).innerHTML = parseInt($api.byId('idd_' + commentsId).innerHTML) + 1;
                if (type == 3) {

                    var jsfun = 'zadNumber("' + commentsId + '");';
                    api.execScript({
                        name: 'comment_xq_win1',
                        frameName: 'comment_xq_frm1',
                        script: jsfun
                    });
                }

            } else {

                api.toast({
                    msg: data.msg,
                    duration: 2000,
                    location: 'middle'
                });

            }

        }, function (data) {

        });

    }

}

// 多个国家手机号验证
var phones = [
    [
        'ar-DZ',
        /^(\+?213|0)(5|6|7)\d{8}$/],
    [
        'ar-SY',
        /^(!?(\+?963)|0)?9\d{8}$/],
    [
        'ar-SA',
        /^(!?(\+?966)|0)?5\d{8}$/],
    [
        'en-US',
        /^(\+?1)?[2-9]\d{2}[2-9](?!11)\d{6}$/],
    [
        'cs-CZ',
        /^(\+?420)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/],
    [
        'de-DE',
        /^(\+?49[ \.\-])?([\(]{1}[0-9]{1,6}[\)])?([0-9 \.\-\/]{3,20})((x|ext|extension)[ ]?[0-9]{1,4})?$/],
    [
        'da-DK',
        /^(\+?45)?(\d{8})$/],
    [
        'el-GR',
        /^(\+?30)?(69\d{8})$/],
    [
        'en-AU',
        /^(\+?61|0)4\d{8}$/],
    [
        'en-GB',
        /^(\+?44|0)7\d{9}$/],
    [
        'en-HK',
        /^(\+?852\-?)?[569]\d{3}\-?\d{4}$/],
    [
        'en-IN',
        /^(\+?91|0)?[789]\d{9}$/],
    [
        'en-NZ',
        /^(\+?64|0)2\d{7,9}$/],
    [
        'en-ZA',
        /^(\+?27|0)\d{9}$/],
    [
        'en-ZM',
        /^(\+?26)?09[567]\d{7}$/],
    [
        'es-ES',
        /^(\+?34)?(6\d{1}|7[1234])\d{7}$/],
    [
        'fi-FI',
        /^(\+?358|0)\s?(4(0|1|2|4|5)?|50)\s?(\d\s?){4,8}\d$/],
    [
        'fr-FR',
        /^(\+?33|0)[67]\d{8}$/],
    [
        'he-IL',
        /^(\+972|0)([23489]|5[0248]|77)[1-9]\d{6}/],
    [
        'hu-HU',
        /^(\+?36)(20|30|70)\d{7}$/],
    [
        'it-IT',
        /^(\+?39)?\s?3\d{2} ?\d{6,7}$/],
    [
        'ja-JP',
        /^(\+?81|0)\d{1,4}[ \-]?\d{1,4}[ \-]?\d{4}$/],
    [
        'ms-MY',
        /^(\+?6?01){1}(([145]{1}(\-|\s)?\d{7,8})|([236789]{1}(\s|\-)?\d{7}))$/],
    [
        'nb-NO',
        /^(\+?47)?[49]\d{7}$/],
    [
        'nl-BE',
        /^(\+?32|0)4?\d{8}$/],
    [
        'nn-NO',
        /^(\+?47)?[49]\d{7}$/],
    [
        'pl-PL',
        /^(\+?48)? ?[5-8]\d ?\d{3} ?\d{2} ?\d{2}$/],
    [
        'pt-BR',
        /^(\+?55|0)\-?[1-9]{2}\-?[2-9]{1}\d{3,4}\-?\d{4}$/],
    [
        'pt-PT',
        /^(\+?351)?9[1236]\d{7}$/],
    [
        'ru-RU',
        /^(\+?7|8)?9\d{9}$/],
    [
        'sr-RS',
        /^(\+3816|06)[- \d]{5,9}$/],
    [
        'tr-TR',
        /^(\+?90|0)?5\d{9}$/],
    [
        'vi-VN',
        /^(\+?84|0)?((1(2([0-9])|6([2-9])|88|99))|(9((?!5)[0-9])))([0-9]{7})$/],
    [
        'zh-CN',
        /^(\+?0?86\-?)?1[345789]\d{9}$/],
    [
        'zh-TW',
        /^(\+?886\-?|0)?9\d{8}$/]];

var tureOrfalse;

function panPhone(phone, quhao) {
    if (!quhao) {
        quhao = '';
    }
    var falseNum = 0;
    console.log('phone|tt ' + quhao + phone);
    for (var i = 0; i < phones.length; i++) {
        if (phones[i][1].test(quhao + phone)) {
            tureOrfalse = 1;
        } else {
            falseNum++;
        }
    }
    if (falseNum == phones.length) {
        tureOrfalse = 0;
    }

    console.log('tureOrfalse|tt ' + tureOrfalse);
    if (quhao) {
        if (!tureOrfalse) {
            api.toast({
                msg: '请输入正确的手机号',
                duration: 2000,
                location: 'middle'
            });
        }
    }
}

// 去0澳洲手机号
function quZero(phone) {
    if (phone.length == 10) {
        if (!phone[0]) {
            return phone.substring(1);
        } else {
            return phone;
        }

    } else {
        return phone;
    }
}

//智问库列表评论数
function changeCommnet1(malId, comment_length) {
    var zmalId = malId;
    var zcomment_length = comment_length;
    $api.byId('idd_' + zmalId).innerHTML = zcomment_length;

}

//智问库
//点赞数加一，点赞图标变蓝
function zadNumber(commentsId) {
    if ($api.byId('id_' + commentsId) == null) {
        return;
    }
    $api.removeCls($api.byId('id_' + commentsId), 'zan3');
    $api.addCls($api.byId('id_' + commentsId), 'zan4');
    $api.byId('idd_' + commentsId).innerHTML = parseInt($api.byId('idd_' + commentsId).innerHTML) + 1;

}

//点赞数减一
function zsubNumber(commentsId) {
    if ($api.byId('id_' + commentsId) == null) {
        return;
    }
    $api.removeCls($api.byId('id_' + commentsId), 'zan4');
    $api.addCls($api.byId('id_' + commentsId), 'zan3');
    $api.byId('idd_' + commentsId).innerHTML = parseInt($api.byId('idd_' + commentsId).innerHTML) - 1;

}

//分享
function fnDian(smdId2, userId2, userNickName2, userImg2) {
    event.stopPropagation();
    var pageParam2 = {
        type: 'fenxiang',
        smdId: smdId2,
        userId: userId2,
        userNickName: userNickName2,
        userImg: userImg2
    };
    shareToOtherApp({
        showType: 3,
        shareType: 2,
        title: '我在留学之家发现了一条超有意思的帖子，赶快来看看吧！',
        description: '留学从这里开始',
        thumb: 'widget://image/share/dongtai.png',
        url: shareServerUrl + 'dongtai_xq.html?smdid=' + smdId2 + '&userid=' + $api.getStorage('allUser').userId
    });

}

// 根据留学状态判断学校
function fnSchool(isGraduation, schoolName) {
    if (isGraduation == 1) {
        return '毕业于[' + schoolName + ']';
    } else if (isGraduation == 2) {
        return '来自于[' + schoolName + ']';
    } else if (isGraduation == 3) {
        if (schoolName) {
            return '想去[' + schoolName + ']';
        } else {
            return '我还没想好';
        }
    } else {
        return '';
    }

}

//动态详情
function openOneZhiWenKuu(el) {
    event.stopPropagation();
    var malId = $api.attr(el, 'malId') || '';
    var winNameee = $api.attr(el, 'winNameee') || '';
    var frmNameee = $api.attr(el, 'frmNameee') || '';
    var type = $api.attr(el, 'type') || '';
    var parame = {
        malId: malId,
        winNameee: winNameee,
        frmNameee: frmNameee,
        type: type
    };
    setTimeout(function () {
        api.closeWin({
            name: 'search_question_win'
        });
    }, 1000);
    setTimeout(function () {
        api.closeWin({
            name: 'label_win'
        });
    }, 1000);
    openWindow('answer_xq_win', '../../html/main3/answer_xq_win.html', parame);
}

//拷贝课程表
function copyToTable(url) {
    if (url.indexOf('share/h5/kcb.html') == -1) {
        api.toast({
            msg: '不是有效的课程表',
            duration: 2000,
            location: 'middle'
        });
        return;
    }
    var copyTable = function (data) {
        if (data.userid == $api.getStorage('allUser').userId) {
            Confirm({msg: '是否打开自己的课程表'}, function (ret, err) {
                if (ret.value.index == 2) {
                    openWindow('kcb_win', 'widget://html/main1/kcb_win.html', {});
                }
            });
        } else {
            Confirm({msg: '是否复制别人课表(自己的课表和学期将会被删除)'}, function (ret, err) {
                var params = {
                    values: {
                        copyUserId: data.userid,
                        copySemesterId: data.semesterid
                    }
                };
                doAjax(COPYTABLE, 'POST', params, function (data) {
                    if (data.code == 200) {
                        api.sendEvent({
                            name: 'changKCB',
                            extra: {
                                type: 2
                            }
                        });
                        api.toast({
                            msg: '拷贝课表成功',
                            duration: 2000,
                            location: 'middle'
                        });
                    } else {
                        api.toast({
                            msg: data.msg,
                            duration: 2000,
                            location: 'middle'
                        });
                    }
                }, function (err) {
                    console.log(JSON.stringify(err));
                });
            });
        }

    };
    var value = url.split('?')[1].split('&');
    var obj = {};
    for (var i = 0; i < value.length; i++) {
        obj[value[i].split('=')[0]] = value[i].split('=')[1];
    }
    if (obj.type == 'kcb') {
        copyTable(obj);
    }

}

//分享
function shareToOtherApp1(config) {
    api.openFrame({
        name: 'z_share1',
        url: 'widget://html/main1/z_share1.html',
        pageParam: config,
        bounces: false
    });
}

function HTMLToText(html) {
    var div = document.createElement('div');
    div.innerHTML = html;
    return div.innerText;
}

/*
*倒计时30分钟
*传参 创建时的时间戳
*返回 xx:xx
*例：CountDown30min('1546587949939');
*/
function CountDown30min(getTime) {
    return (Number(getTime) + 1800000 - Number(new Date().getTime())) > 0 && 1800000 > (Number(getTime) + 1800000 - Number(new Date().getTime())) ? parseInt(parseInt((Number(getTime) + 1800000 - Number(new Date().getTime())) / 1000) / 60) +
        ':' + parseInt((Number(getTime) + 1800000 - Number(new Date().getTime())) / 1000) % 60 : '0:0';
}

function CountDown30min11(getTime) {
    return (Number(getTime) + 1800000 - Number(new Date().getTime())) > 0 && 1800000 > (Number(getTime) + 1800000 - Number(new Date().getTime())) ? parseInt(parseInt((Number(getTime) + 1800000 - Number(new Date().getTime())) / 1000) / 60) +
        '分' + parseInt((Number(getTime) + 1800000 - Number(new Date().getTime())) / 1000) % 60 : '0分0';
}

/**
 *打开Frame例子：
 var parame  = {
	 	 rowid : rowid
	  }
 openFrame("chat_win", "chat_win.html",parame);
 *
 */
//打开一个frame
function openFrame(name, url, pageParam) {
    if ($api.byId('header')) {
        var headerH = $api.offset($api.byId('header')).h;
    } else {
        var headerH = 0;
    }
    var pageParams = api.pageParam;
    var pageParamss = extend({}, [
        pageParams,
        pageParam]);
    api.openFrame({
        name: name,
        url: url,
        hScrollBarEnabled: false,
        vScrollBarEnabled: false,
        bounces: false,
        rect: {
            x: 0,
            y: headerH,
            w: 'auto',
            h: 'auto',
            marginBottom: api.safeArea.bottom  //安全区域 适配ios
        },
        pageParam: pageParamss
    });
}

//////////////////////分割价格/////////////////////
function splitPrice(numPrice) {
    // alert(numPrice);
    if (numPrice.indexOf('.') != -1) {
        return numPrice.split('.');
    } else {
        return [
            numPrice,
            '00'];
    }
}

//////////////////////商品总价/////////////////////
function totalPrice(num, Price) {

    return parseInt(num) * Price;

}

/////////////////////我的-我的订单-取消订单////////////////////
function fnCancel(name, frame, order_id, type) {
    api.openFrame({
        name: 'z_cancel',
        url: '../../html/main4/z_cancel.html',
        hScrollBarEnabled: false,
        vScrollBarEnabled: false,
        bounces: false,
        rect: {
            x: 0,
            y: 0,
            w: 'auto',
            h: 'auto',
            marginBottom: api.safeArea.bottom  //安全区域 适配ios
        },
        pageParam: {
            namee: name,
            framee: frame,
            order_id: order_id,
            type: type
        }
    });
}

/////////////////////我的-我的订单-确认收货////////////////////
function fnShou(name, frame, order_id, type) {
    api.openFrame({
        name: 'z_shou',
        url: '../../html/main4/z_shou.html',
        hScrollBarEnabled: false,
        vScrollBarEnabled: false,
        bounces: false,
        rect: {
            x: 0,
            y: 0,
            w: 'auto',
            h: 'auto',
            marginBottom: api.safeArea.bottom  //安全区域 适配ios
        },
        pageParam: {
            namee: name,
            framee: frame,
            order_id: order_id,
            type: type
        }
    });
}

/////////////////////我的-我的订单-删除////////////////////
function fnDelete(name, frame, order_id, type) {
    api.openFrame({
        name: 'z_delete',
        url: '../../html/main4/z_delete.html',
        hScrollBarEnabled: false,
        vScrollBarEnabled: false,
        bounces: false,
        rect: {
            x: 0,
            y: 0,
            w: 'auto',
            h: 'auto',
            marginBottom: api.safeArea.bottom  //安全区域 适配ios
        },
        pageParam: {
            namee: name,
            framee: frame,
            order_id: order_id,
            type: type
        }
    });
}

/////////////////////我的-我收到的订单-确认发货////////////////////
function fnFa(name, frame, order_id, type) {
    api.openFrame({
        name: 'z_fahuo',
        url: '../../html/main4/z_fahuo.html',
        hScrollBarEnabled: false,
        vScrollBarEnabled: false,
        bounces: false,
        rect: {
            x: 0,
            y: 0,
            w: 'auto',
            h: 'auto',
            marginBottom: api.safeArea.bottom  //安全区域 适配ios
        },
        pageParam: {
            namee: name,
            framee: frame,
            order_id: order_id,
            type: type
        }
    });
}

//转换图片字符串为数组
function zhuangArrayImg3(img) {
    if (img.length - 1 == img.lastIndexOf(',')) {
        var getArray = img.substring(0, img.lastIndexOf(',')).split(',');
        return getArray;
    } else {
        var getArray = img.split(',');
        return getArray;
    }
}
//进入投诉页面
function opentousu() {
  var params={

  };
  openWindow('tousu_win', './tousu_win.html',params);

}
//任务详情
function taskXq(el,search){
  search = search||'';
  var taskId = $api.attr(el, 'taskId');
  if(taskId=='0'){
  	return
  }else{
  	var params={
      taskId:taskId,
      search:search
  };
      openWindow('task_xq_win','../../html/main2/task_xq_win.html',params);
  }

}

//修改时间格式2019/04/11 15:24
function changeTimeee(time){
  var arr=time.replace(/-/g, '/');
  var index=arr.lastIndexOf(":");
  var timeAll=arr.slice(0,index);
  return timeAll
}
//2019/04/11
function changeTimeee1(time){
  var arr=time.replace(/-/g, '/');
  var arr1=arr.split(' ');
  var arr2=arr1[0]
  return arr2;
}
//图片字符串变成数组
function zhuangArrayImg (img) {

  var getArray = img.split(',');
  return getArray;
}



///////////////////
/**
 *打开win例子：
 var parame  = {
	 	 rowid : rowid
	  }
 openWindow("chat_win", "chat_win.html",parame);
 *
 */
var openWindow = function (name, url, pageParam) {
    if (!pageParam) {
      pageParam = '';
    }
    window.location.href = url+'?'+encodeURI(JSON.stringify(pageParam));//"./fast_login_win.html?id=11";
};
function GetRequest() {
    var url = location.search; //获取url中"?"符后的字串
    if (url.length <= 1) {
      return
    }
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        theRequest = JSON.parse(decodeURI(str));
        console.log(theRequest);
    }
    return theRequest;
}
var apiPageParam = GetRequest();
function tanKuang(message){

var toast = new auiToast();

toast.fail({
    title:message,
    duration:8000
});


}
